Pointers

Getting the Address of a Variable

  • Each variable in program is stored at a unique address

  • Use address operator & to get address of a variable:

int num = -54;
cout << &num; // prints address of num
                // in hexadecimal

Pointer Variables

  • Pointer variable : Often just called a pointer, it's a variable that holds an address

  • Because a pointer variable holds the address of another piece of data, it "points" to the data

  • Definition:

    • int *intptr;

  • Read as:

    • “intptr can hold the address of an int”

  • Spacing in definition does not matter:

int * intptr; // same as above
int* intptr; // same as above
  • Assigning an address to a pointer variable:

int *intptr;
intptr = &num;
Memory Layout

The Inderection Operator

  • The indirection operator (*) dereferences a pointer.

  • It allows you to access the item that the pointer points to.

int x = 42;
int *intptr = &x;
cout << *intptr << endl; //This prints 42
  • Array name can be used as a pointer constant:

int vals[] = {4, 7, 11};
cout << *vals; // displays 4

int vals[] = {4,7,11}, *valptr;
valptr = vals;

cout << *(valptr+1); //displays 7
cout << *(valptr+2); //displays 11

Array Access

If a is an array, and i is an index into the array, then

a[i] and *(a+i) mean exactly the same thing

(As a matter of fact, when the C++ compiler sees an expression like a[i], it converts it to *(a+i) before translating it into machine code.)

Pointer Arithmetic

Last updated

Was this helpful?