



Pointers in C
Pointers in C are variables which hold the address of the memory used to store other variables. For example, say we have an int variable k:
int k = 17;
When the compiler sees this statement it does two things: (i) it creates a reservation in memory (generally 4 bytes in size for an int, but this depends on the system and compiler), and assigns the value 17 to this memory; (ii) the variable k is added to the symbol table along with the address of the memory assigned to the variable.
A pointer is a variable that stores a memory location, e.g.
int *my_ptr = k;
This statement is read by the compiler as "create a new variable called my_ptr which is going to hold the address of the int variable k". We can see why the variable is called a pointer, as it points to the location where the value of a variable is held in memory. It is generally considered bad practice and dangerous to declare a pointer without initialising it as this can cause potential problems with the memory, therefore most ANSI compliant compilers have a macro defined which sets the memory location of a pointer to null:
int *my_ptr2 = NULL;
This is called a null pointer. If we now want to store the address of our variable k in this new pointer we use the expression:
my_ptr2 = &k;
This is read by the compiler as "assign the memory location of the int variable k to the pointer variable my_ptr2".
Finally there is the dereferencing operator * which is used to access the value stored in a pointer. Continuing the examples above, we can change the value stored in the int variable k by:
*my_ptr2 = 34;
Again, the compiler reads this as "assign the int value 34 to the memory pointed to by the pointer my_ptr2". The value 34 is now stored in the variable k.
Summary
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Create a pointer:
<type> *<pointer_name>
<type> *<pointer_name> = NULL;
<type> *<pointer_name> = <variable of type type>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Assign an address to a pointer:
<pointer_name> = &<variable>
The & operator is used to access the location of the memory used to store the variable.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Assign a value to the address pointed to by the pointer:
*<pointer_name> = <value>
* is called the dereference operator and accesses the contents of the memory location.
Example
/* * File: main.c
* Author: jimmy
*
* Created on 03 February 2010, 12:33 */
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
int main()
{
printf("\nThe size of a signed char is %d bytes", sizeof(signed char));
printf("\nThe size of a short int is %d bytes", sizeof(short int));
printf("\nThe size of an int is %d bytes", sizeof(int));
printf("\nThe size of a long int is %d bytes", sizeof(long int));
printf("\nThe size of a long long int is %d bytes", sizeof(long long int));
printf("\n\n");
int k = 17;
int *my_ptr = k;
printf("\n\nThe size of %s is %d bytes, it's value is %d and it's location is %p", "my_ptr", sizeof(*my_ptr), my_ptr, &my_ptr);
printf("\n\n");
}