Before going to concept of pointer it is necessary to distinguish between normal variable and pointer variable. Normal variable always stores value and pointer variable always store address of appropriate type variable. In pointer terminology two operators are used namely & operator (ampersand) and * operator (asterisk). Here & operator means address of operator and * operator means value at address operator. So pointer is also known as reference variable as it refers the address of a variable and indirectly points to that variable.
Syntax for declaring pointer variable is as follows
data type * pointer variable name;
example of declaring pointer variable is as follows
int * p;
It is necessary to understand what is the meaning of above statement. It means p is a pointer variable which is able to hold address of an integer variable only and not the address of any other type variable.
int * p;
p=&x; This statement is valid because p is an integer pointer and it is able to hold address of integer x.
Real appeal of pointer is that once we get the address of a variable, we can operate indirectly on the variable whose address is hold by the pointer.
So if we write *p=670; then it means that value of x now becomes 670.
Real use of pointer comes into picture when we need to pass arguments to function and want to access the actual parameters inside the function. In this case we pass parameters by reference i.e. by using pointer.
Following program shows use of pointer in function.
void swap(int * , int *);
printf("Enter any two numbers\n");
printf("\nBefore swapping value of a is %d and value of b is %d",a,b);
printf("\nAfter swapping value of a is %d and value of b is %d",a,b);
void swap(int * x, int * y)
*x = *y;
*y = temp;
Here in above example function pass address of a and b, not values. So that in function re declaration pointer x and y are used to receive addresses of a and b respectively. Inside the function when changes are made in *x and *y, it ultimately reflects in calling function. So though function does not return any value still it swaps value of a and b in main function.
Especially in character array, when it not known in advance what will be the size of an character array. In such case character pointer variable is used to store required string with exactly required space and hence avoid the declaration such as char name, where 30 may be more that required or may be less that required space.
suppose we declare a statement like
char * name ;
Then by using
scanf("%s",name); we can read a string of any length without wastage of memory space.
Pointers may be used for structure, class also. It means we can use pointer on derived data types also.
In general we can assign pointer to every entity that has address.