A pointer is a special kind of variable. Pointers are designed for storing memory address i.e. the address of another variable. Declaring a pointer is the same as declaring a normal variable except you stick an asterisk '*' in front of the variables identifier. There are two new operators you will need to know to work with pointers. The "address of" operator '&' and the "dereferencing" operator '*'. Both are prefix unary operators. When you place an ampersand in front of a variable you will get it's address, this can be stored in a pointer variable. When you place an asterisk in front of a pointer you will get the value at the memory address pointed to. Here is an example to understand what I have stated above. This will produce following result. Pointers and Arrays y is of type pointer to character (although it doesn't yet point anywhere). We can make y point to an element of x by either of Since x is the address of x[0] this is legal and consistent. Now `*y' gives x[0]. More importantly notice the following: Pointer Arithmetic: On a typical 32-bit machine, *ip would be pointing to 5 after initialization. But ip++; increments the pointer 32-bits or 4-bytes. So whatever was in the next 4-bytes, *ip would be pointing at it.#include
int main()
int my_variable = 6, other_variable = 10;
int *my_pointer;
printf("the address of my_variable is : %p\n", &my_variable);
printf("the address of other_variable is : %p\n", &other_variable);
my_pointer = &my_variable;
printf("\nafter \"my_pointer = &my_variable\":\n");
printf("\tthe value of my_pointer is %p\n", my_pointer);
printf("\tthe value at that address is %d\n", *my_pointer);
my_pointer = &other_variable;
printf("\nafter \"my_pointer = &other_variable\":\n");
printf("\tthe value of my_pointer is %p\n", my_pointer);
printf("\tthe value at that address is %d\n", *my_pointer);
return 0;
}the address of my_variable is : 0xbfffdac4
the address of other_variable is : 0xbfffdac0
after "my_pointer = &my_variable":
the value of my_pointer is 0xbfffdac4
the value at that address is 6
after "my_pointer = &other_variable":
the value of my_pointer is 0xbfffdac0
the value at that address is 10
The most frequent use of pointers in C is for walking efficiently along arrays. In fact, in the implementation of an array, the array name represents the address of the zeroth element of the array, so you can't use it on the left side of an expression. For example: char *y;
char x[100]; y = &x[0];
y = x; *(y+1) gives x[1]
*(y+i) gives x[i]
and the sequence
y = &x[0];
y++;
leaves y pointing at x[1].
C is one of the few languages that allows pointer arithmetic. In other words, you actually move the pointer reference by an arithmetic operation. For example:int x = 5, *ip = &x;
ip++;
Pointer arithmetic is very useful when dealing with arrays, because arrays and pointers share a special relationship in C.
Pointing to Data
Labels: C Learning