COMS 3157 Advanced Programming

04 - pointers

Reading

Pointers and addresses

A pointer is a variable that holds memory addresses:

int x = 1, y = 2;

int *p; // p is a pointer variable

p = &x; // that holds an address of an int variable

y = *p; // y is now 1

*p = 0; // x is now 0.  Note that *p is an l-value.

p = &y; // p now points to y

*p = 2; // y is now 2, x is still 0

++*p;   // y is now 3

(*p)++; // y is now 4. Note that * and ++ go right-to-left.

A pointer is typed:

int      i = 1234;
double   d = 3.14;

int    *pi = &i; 
double *pd = &d;

pi = pd;  // compiler error

pi = (int *)pd;  // compiles, but you better know what you're doing...

void *pv;  

pv = pi;  // void pointer can hold any type of pointer

i = *pv;  // compiler error - can't dereference a void pointer

i = *(int *)pv;  
pi = (int *)pv;  // you get back the int pointer by casting

NULL pointer

Simulating call-by-reference using pointers

C is “call-by-value” language