Pointers Introduction
A pointer is a reference to a data object or a function. Pointers have many uses: defining “call-by-reference” functions, and implementing dynamic data structures such as chained lists and trees, to name just two examples.
Very often the only efficient way to manage large volumes of data is to manipulate not the data itself, but pointers to the data. For example, if you need to sort a large number of large records, it is often more efficient to sort a list of pointers to the records, rather than moving the records themselves around in memory. Similarly, if you need to pass a large record to a function, it’s more economical to pass a pointer to the record than to pass the record contents, even if the function doesn’t modify the contents.
Consider the declaration :
int a = 1 ;
This declaration tells the C compiler to:
(a) Reserve space in memory to hold the integer value.
(b) Associate the name a with this memory location.
(c) Store the value 1 at this location.
We may represent a’s location in memory by the following memory map.
We see that the computer has selected memory location 3268536 as the place to store the value 3. The location number 3268536 is not a number to be relied upon, because some other time the computer may choose a different location for storing the value 1. The important point is, a’s address in memory is a number.
Example
#include<stdio.h> int main( ) { int a = 1 ; printf ( "\nAddress of a = %u", &a ) ; printf ( "\nValue of a = %d", a ) ; getchar(); return 0; }
Look at the first printf( ) statement carefully. ‘&’ used in this statement is C’s ‘address of’ operator. The expression &a returns the address of the variable a, which in this case happens to be 3268536. Since 3268536 represents an address, there is no question of a sign being associated with it. Hence it is printed out using %u, which is a format specifier for printing an unsigned integer. We have been using the ‘&’ operator all the time in the scanf( ) statement.
The other pointer operator available in C is ‘*’, called ‘value at address’ operator. It gives the value stored at a particular address. The ‘value at address’ operator is also called ‘indirection’ operator.
Example
#include<stdio.h> int main( ) { int a = 3 ; printf ( "\nAddress of a = %u", &a ) ; printf ( "\nValue of a = %d", a ) ; printf ( "\nValue of a = %d", *( &a ) ) ; getchar(); return 0; }