Syntax of Pointers in C


Here are the basic ways to use pointers in C that you'll find handy to complete today's lab.  Note that the full explanation of the syntax of pointers is in "Pointers" (Lecture 12).

 

Symbol Meaning Name Usage
"address of" Address Operator &foo - the address of foo
* "the value that this pointer points to" Dereference/Star Operator *fooPtr - the value that the pointer 'fooPtr' points to

 

int num1, num2;

float avg;

avg = CalcAverage(num1, num2);

This passes a copy of the values of num1 and num2 to the CalcAverage function.  CalcAverage() cannot modify the original num1 and num2 since it does not have their addresses, only a copy of their values.

int num1, num2;

Swap(&num1, &num2);

This passes the addresses of num1 and num2 to swap its elements in Swap().  Swap() can modify the original num1 and num2 since it has their addresses.

 

Just like other variables like ints, doubles, and chars, pointers need to be initialized. When a pointer is first declared, it just contains some garbage value that points to a random area of memory.

The pointer fooPtr hasn't been assigned any memory to point to, so incrementing the value pointed to by the garbage address of fooPtr usually leads to a segmentation fault.  Fix it with this:

So now fooPtr points to the variable foo.

In order to increment the value contained in foo, we have to use parentheses.

So if we did the following without the parentheses, we would be incrementing the value of the pointer:

What we did was increment the value of the pointer, so if the address fooPtr pointed to was FE00 to start with, the line above would make fooPtr now point to FE04. So it doesn't even point to foo anymore - ooops !!