|
Pointers and References in C/C++
An Introduction |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
int i;
i is added to the name tablei is designated a value typeint
&i
i = 5;
i is assigned the value 5
*
int *ptr;
&ptr
ptr = &i;
* operatorint j; j = *ptr;
int *otherptr; otherptr = &i;
(*otherptr) = 9;
int a[4];
a,
&a and &a[0]
all evaluate to the same thingsizeof and
&)
cout << "The contents of a: " << a << "\n";
cout << "The address of a: " << &a << "\n";
cout << "The address of a[0]: " << &a[0] << "\n";
cout << "The address of a[1]: " << &a[1] << "\n";
cout << "The address of a[2]: " << &a[2] << "\n";
cout << "The address of a[3]: " << &a[3] << "\n";
[] is evaluated before
&
int array is an int
a[0] = 100;
a[1] = 101;
a[2] = 102;
a[3] = 103;
int
array is a pointer to an int
int *thirdptr;
thirdptr = &a[0];
int
does not change its contents by 1, it changes
its contents by the size of the data type
it is pointing to
thirdptr+1 is 0x22FF54
*(thirdptr) is the same as a[0]
*(thirdptr+1) is the same as a[1]
*(thirdptr+2) is the same as a[2]
*(thirdptr+3) is the same as a[3]
/**
*
* An example that uses a char*
*
* @author Prof. David Bernstein, James Madison University
* @version 1.0
*/
#include <iostream>
#include <string>
using namespace std;
/**
* Find the index of the first occurence
* of a character in a string.
*
* @param string_ptr A pointer to the string
* @param lookFor The character to look for
*
* @side-effects None (Or are there? Is string_ptr changed?)
*
* @return The index of the first occurence of the
* character (0 based) or -1 if the character
* is not contained in the string
*/
int indexOf(char* string_ptr, char lookFor) {
int index;
index = 0;
while ((*string_ptr != lookFor) && (*string_ptr != '\0')) {
++string_ptr;
++index;
}
if (*string_ptr == '\0')
index = -1;
return index;
}
/**
* The entry point of the application
*/
int main(void) {
char line[80];
strcpy(line, "This is a line.\n");
cout << indexOf(line, 'A') << "\n";
cout << indexOf(line, 'i') << "\n";
cout << indexOf(line, '\n') << "\n";
cout << line;
}
&
int &r = i;
r now refers to i so
it has the same address and the same contents
r = 8;
r and hence to
i
#ifndef edu_jmu_cs_Weight_h
#define edu_jmu_cs_Weight_h
/**
* A very simple weight class (used to demonstrate memory
* allocation for objects)
*
* @author Prof. David Bernstein, James Madison University
* @version 1.0
*/
class Weight {
public:
int pounds, ounces;
/**
* Explicit Value Constructor
*
* @param lbs The number of pounds in this Weight
* @param oz The number of ounces in this Weight
*/
Weight(int lbs, int oz);
};
#endif
#include "Weight.h"
Weight::Weight(int lbs, int oz) {
pounds = lbs;
ounces = oz;
}
Weight w(6,11);
Weight object, its
constructor is called, and the two member attributes
are initialized