Definition


Pointers are special variables that store addresses.

Since the length of an address is the word size, the size of a pointer is also the word size. (8-bytes in a 64-bit machine).

The pointer data type must also encode size information.

Untitled

Pointer Arithmetic


Consider Code:

z = &y +3;

We get the address of y, “add 3” to it, and then store the result in z.

However, since the expression &y is an address, pointer arithmetic is going to apply. So instead of taking the address of y, 0x18, and adding 3 to it to get the 0x1B, we need to scale by the size of an int, which is 4, and add 12 to get 0x24 (0x18 = 16 + 8 = 24, 24 + 12 = 36, 36 = 32 + 4 = 216 + 41 = 0x24). This is equivalent to moving the pointer forward by 3 ints!

Notice: void pointers do not have scale, use extreme caution

Syntax in C


//either of these declaration is legal
//type* pointer
//type *pointer

//& in front of a variable name returns its address
//* in front of a point's name returns the value it's pointed to 

#include <stdio.h>
int main() {
  int q = 7;
  int* p = &q;  // notice the pointer declaration and use of & operator
  printf("p = %p\\n", p); //p = 0x7ffcafbb7fb4(an address)
  printf("*p's value is %i\\n", *p); //*p's value is 7
}