Declaration & Syntax In Pointer

Pointers are declared by using the * in front of the variable identifier. For example:
int *ip;
float *fp = NULL;

This declares a pointer, ip, to an integer. Let’s say we want ip to point to an integer. The second line declares a pointer to a float, but initializes the pointer to point to the NULL pointer. The NULL pointer points to a place in memory that cannot be accessed. NULL is useful when checking for error conditions and many functions return NULL if they fail.
int x = 5;
int *ip;

ip = &x;

We first encountered the & operator first in the I/O section. The & operator is to specify the address-of x. Thus, the pointer, ip is pointing to x by assigning the address of x. This is important. You must understand this concept.

This brings up the question, if pointers contain addresses, then how do I get the actual value of what the pointer is pointing to? This is solved through the * operator. The * dereferences the pointer to the value. So,
printf(“%d %d\n”, x, *ip);
would print 5 5 to the screen.

There is a critical difference between a dereference and a pointer declaration:
int x = 0, y = 5, *ip = &y;
x = *ip;

The statement int *ip = &y; is different than x = *ip;. The first statement does not dereference, the * signifies to create a pointer to an int. The second statement uses a dereference.
Remember the swap function? We can now simulate call by reference using pointers. Here is a modified version of the swap function using pointers:
void swap(int *x, int *y) {

int tmp;

tmp = *x;

*x = *y;

*y = tmp;

}

int main() {

int a = 2, b = 3;

swap(&a, &b);

return EXIT_SUCCESS;

}

This snip of swapping code works. When you call swap, you must give the address-of a and b, because swap is expecting a pointer. Why does this work? It’s because you are giving the address-of the variables. This memory does not “go away” or get “popped off” after the function swap ends. The changes within swap change the values located in those memory addresses.