The pointer in c language is a variable, which stores address of another variable. Whenever we declare a variable in c, it takes some space in memory and each memory has a unique address in hexadecimal numbers.
Pointers : Key Points in C
- Normal variables stores value, and pointer variable stores address.
- The pointer in c is used to allocate memory dynamically (at run time).
- C language has two symbols ( & and *) to work with pointers.
- & – returns the address of a variable in C.
- * – returns the value of a variable, pointed by a pointer variable.
- %p – Format in c to print pointer reference.
Example 1: Print address of a variable in C language.
#include<stdio.h>
int main()
{
int n=10;
printf("\n %d",n); // print value of n.
printf("\n %p",&n); //print address of n
return 0;
}
Sample Output:10
0x7ffe676efd6c
Example 2: Declare and use of pointer variables in c language.
#include<stdio.h>
int main()
{
int n, *pt;
n=10;
pt=&n;
printf("\nValue : %d", n); // print value of n.
printf("\nAddress %p", pt); //print address of n
printf("\nValue : %d", *pt); // print value of n.
return 0;
}
Sample Output:
Value : 10
Address 0x7ffd90c6b3b4
Value: 10
Whenever we use a pointer variable with (*) symbol, then it refers to the variable that’s address is stored in the pointer variable.
Address of a variable will be different on your pc, and address can change every time when you run the program.
Double Pointer in C (Pointer to Pointer)
As we know that the pointer variables are used to store the address of a normal variable, to store the
Example 3: C program of double pointer implementation in C
//to declare a double pointer in c, you need to use double **.
#include<stdio.h>
int main()
{
int n,*a,**b;
n=10;
a=&n;
b=&a;
printf("\n %d",n); //print value of n
printf("\n %p",a); //print address of n,
printf("\n %p",b); //print address of a
printf("\n %d",*a); //print value of n
printf("\n %p",*b); //print address of n
printf("\n %d",**b); //print value of n
return 0;
}
sample Output:
10
0x7ffda19aee74
0x7ffda19aee78
10
0x7ffda19aee74
10
In the above code **b is same as *(*b), means *(a), because *b refers a.
Pointer with Array in C.
#include<stdio.h>
int main()
{
int n[5],i,*b;
for(i=0;i<5;i++)
{
printf("\nEnter a number");
scanf("%d",&n[i]);
}
b=&n[0]; //pointer points 0th element of the array
//It will print 5 times value of 0th element only
for(i=0;i<5;i++)
{
printf("%d\n",*b);
}
//It will print value of array, because of increment in pointer address
printf("Printing Array with Pointer Increment\n");
for(i=0;i<5;i++)
{
printf("%d\n",*b);
b++;
}
return 0;
}