A pointer is a variable pointing to the address of another variable. It is declared along with an asterisk symbol (*). A pointer can also be used to refer to another pointer function. A pointer can be incremented/decremented, i.e., to point to the next/ previous memory location. The purpose of pointer is to save memory space and achieve faster execution time.
The syntax to declare a pointer is as follows:
datatype *var1
The syntax to assign the address of a variable to a pointer is:
datatype var1, *var2; var2=&var1
A simple program for pointer illustration is given below:
#include <stdio.h> int main() { int a=20; //variable declaration int *p; //pointer variable declaration p=&a; //store address of variable a in pointer p printf("Address stored in a variable p is:%x\n",p); //accessing the address printf("Value stored in a variable p is:%d\n",*p); //accessing the value return 0; }
Output:-
Address stored in a variable p is:60ff08 Value stored in a variable p is:20
Operator | Meaning |
---|---|
* | Serves 2 purpose 1 . Declaration of a pointer 2 . Returns the value of the referenced variable |
& | Serves only 1 purpose Returns the address of a variable |
Advantages of Pointers in C:-
- Pointers provide direct access to memory
- Pointers provide a way to return more than one value to the functions
- Reduces the storage space and complexity of the program
- Reduces the execution time of the program
- Provides an alternate way to access array elements
- Pointers can be used to pass information back and forth between the calling function and called function.
- Pointers allows us to perform dynamic memory allocation and deallocation.
- Pointers helps us to build complex data structures like linked list, stack, queues, trees, graphs etc.
- Pointers allows us to resize the dynamically allocated memory block.
- Addresses of objects can be extracted using pointers
Disadvantages of Pointers in C:-
- Uninitialized pointers might cause segmentation fault.
- Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to memory leak.
- Pointers are slower than normal variables.
- If pointers are updated with incorrect values, it might lead to memory corruption.
Basically, pointer bugs are difficult to debug. Its programmers responsibility to use pointers effectively and correctly.