A pointer is a variable that stores the address of another variable. Pointers are much used in C, partly because they are sometimes the only way to express a computation, and partly because they usually lead to more compact and efficient code than that can be obtained in other ways.
Pointers and arrays are closely related to each other because the array name is a pointer constant. Memory can be visualized as an ordered sequence of consecutively numbered storage locations.
A data item stored in memory in one or more adjacent storage locations depends on its type. That is the number of memory locations required depends on the type of a variable.
The address of a data item is the address of its first storage location. This address can be stored in another data item and manipulated in a program. Some use of pointers are,
- Passing the argument by reference.
- Passing array as the argument.
- Processing arrays more efficiently because array name itself is a pointer.
- Data structure such as linked list.
- Holding address returned by memory allocation.
Use of Pointer
Pointers are more efficient in handling the data array. They are used to manipulate arrays more easily by moving pointers them instead of moving the arrays themselves.
Pointers reduce the length and complexity of a program. Pointers are used to return more than one value from a function. Pointers are used to create complex data structures such as linked lists trees etc. The pointer increases execution speed.
The pointer is used to communicate information about memory which returns the location of free memory.
Declaration of pointer variables. A pointer should be declared before its use as any other variable. The data type of the pointer is the data type of the variable to which it is pointing.
A pointer variable is defined by using an indirection symbol “*” using this operator, it becomes possible to point to the address of another variable. A pointer variable is declared as follows.
eg. int *ptr;
Here int indicates that the pointer will point to the variable of integer type ‘*’ indicates the pointer variable and ptr is the name of the pointer variable that points to the integer variable. When pointer is declared, it doesn’t points to anywhere.
int a, *p,*q;
printf("Enter the value of a:");
printf("value of a = %dt Address=%dn",a,&a);
printf("value of a = %dt Address=%dn",*p,p);
printf("value of a = %dt Address=%dn",**q,*q);