The pointer in C language is a variable which stores the address of another variable.
If we want to store an address of a variable to another variable then the variable is called pointer.
It is declared along with an asterisk symbol (*). The syntax to declare a pointer is as follows:
int *p;
Assigning and accessing variable:
#include <stdio.h>
int main()
{
int a;
int *p;
scanf("%d", &a);
p = &a;
printf("%p\n", p);
printf("%d\n", *p);
return 0;
}
Different types of pointers
There are four types of pointers, they are:
- Null Pointer
- Void Pointer
- Wild Pointer
- Dangling Pointer
Null Pointer:
A pointer that is not assigned any value but NULL is known as the NULL pointer.
If we don't have any address to be specified in the pointer at the time of declaration, we can assign NULL value. It will give a better approach.
Syntax:
Int *p = NULL;
Example:
#include<stdio.h>
int main(){
int *p = NULL;
printf(“p=%d”,*p);
}
Void Pointer:
When a pointer is declared with a void keyword, then it is called a void pointer. To print the value of this pointer, you need to typecast it.
Syntax:
void *p;
Example:
#include<stdio.h>
int main()
{
int a=2;
void *p;
p= &a;
printf("After Typecasting, a = %d", *(int *)p);
return 0;
}
Wild Pointer:
A wild pointer is only declared but not assigned an address of any variable. They are very tricky, and they'll reason segmentation errors.
Example:
#include<stdio.h>
int main(){
int *p;
printf(“p=%d”,*p);
return 0;
}
Dangling Pointer:
A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p=(int *)malloc(sizeof(int));
*p = 5;
free(p);
//now this p is known as dangling pointer.
printf(“After deallocating its memory *p=%d”,*p);
return 0;
}
Pointer to Pointer
A pointer will indirectly point to a variable via another pointer.
Something like this: pointer of pointer of pointer of pointer of variable
Example:
#include <stdio.h>
int main()
{
int a = 5;
int *p = &a;
int **q = &p;
printf("%d\n", a);
printf("%p\n", p);
printf("%p\n", q);
**q = 7;
printf("%d\n", a);
return 0;
}
Pass by Value and Pass by Reference
We will pass by reference instead of pass by value.
Example:
#include <stdio.h>
int swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int x = 5, y = 7;
printf("Before swapping x=%d , y=%d\n", x, y);
swap(&x, &y);
printf("After swapping x=%d , y=%d\n", x, y);
return 0;
}
Top comments (2)
Hi. I believe you have a small error in the dangling pointer example.
Proposal:
Hopefully my proposal is OK. I haven't done
C
in a very long time.Thanks @webjose 🎯❤