A pointer or dereferencing operator in C is a powerful feature we found in C and C++. Let us see what is the point in C.
A pointer is a variable which holds the address of another variable, the direct access of the memory location. It is always initialized with a * symbol shown below.
Syntax Of Pointer:
datatype *variablename;
variablename=&var1;
For Example:
#include<stdio.h> int main(){ int *n; int a=10; n=&a; printf("the value of a is %d",a); printf("\nthe address of a is %d",n); return 0; }
Here in the above program it shows the way to initialize and use a pointer in a program.
Output:
Types Of Pointer
The most commonly used pointers are:
Null pointer:
A null pointer is a pointer that holds a null value, which is assigned with a null value during the declaration of a pointer.
For example:
#include<stdio.h> int main(){ int *n=null; printf("the address of the pointer is %d",n); return 0; }
Output:
Void pointer:
A void pointer is a pointer that is not initialized with a standard data type but is initialized with a void keyword. A void pointer is also known as a generic pointer.
Example:
#include<stdio.h> int main(){ void *n=NULL; printf("The address of the pointer is %d",n); return 0; }
Here in this program we can see how a void pointer is initialized and used.
Output:
Wild pointer:
A pointer which is not initialized to anything is called a wild pointer.
Example:
#include<stdio.h> int main(){ int *n; printf("The address of the pointer is %d",n); return 0; }
Output:
Here the above program shows how a wild pointer is initialized and used.
Dangling pointer:
When a pointer holds the address or memory location which has been deleted or freed is called a dangling pointer.
Example:
#include<stdio.h> #include<stdlib.h> int main(){ int *n=(int *)malloc(sizeof(int)); free(n); n=NULL; printf("The address of the pointer is %d",n); return 0; }
Here the above program shows how a dangling pointer is used.
Output:
Let us take an example to demonstrate pointer, a program to swap two values of a variable using pointer.
#include<stdio.h> void swap(int *x, int *y) { int t; t=*x; *x=*y; *y=t; } int main(){ int a,b; printf("\nEnter the value of the two numbers to be swapped"); scanf("%d%d",&a,&b); printf("\nThe values before swapping %d %d",a,b); swap(&a,&b); printf("\nThe values after swapping %d %d",a,b); return 0; }
Here in the above program it shows how to swap two variables using a pointer.
The addresses are stored and passed in a swap function and the addresses are swapped which results in the values in the variables to get swapped.
Hence through this mechanism the values of the variables get swapped.
Output:
Hence, we end this topic on pointers in C. Hope we have cleared all your doubts.
Please share and comments on this topic and if you find anything to add and improve the article then WhatsApp me.