Pointer:
The pointer in C language is a special variable which stores the address of
another variable of same type. The size of a pointer is 4 byte.
The pointer in C language can be declared using * (asterisk symbol). It is
also known as indirection pointer used to dereference a pointer.
Declaration of Pointer:
The general form of a pointer variable declaration is –
data_type *var_name;
Ex:
int *a; //pointer to int
char *c; //pointer to char
Initialization of pointer:
Ex:
int n=50;
int *p;
p=&n;
printf(“%d”,p); // P contains an address of variable n. this statement print address.
printf(“%d”,*p); // Dereference an address.
Ex: Write a program in C to input value of two variable and swap using pointer.
#include<stdio.h>
void main()
{
int x, y, temp,*p1,*p2;
clrscr();
printf(“Input value of x & y”);
scanf(“%d%d”,&x,&y);
p1=&x;
p2=&y;
temp=*p1;
*p1=*p2;
*p2=temp;
printf(“Swap Value X=%d Y=%d”,*p1,*p2);
getch();
}
Pointer Arithmetic in C:
Following arithmetic operations are possible on the pointer in C language:
a) Addition
b) Subtraction
c) Comparison
d) Increment.
e) Decrement
a) Pointer Addition:
Ex:
int x=4, y=5, z, *p1, *p2;
p1=&x;
p2=&y;
z=*p1+*p2;
printf(“Addition =%d”,z);
b) Pointer Subtraction:
Ex:
int x=4, y=5, z, *p1, *p2;
p1=&x;
p2=&y;
z=*p1-*p2;
printf(“Subtraction =%d”,z);
c) Pointer Comparison:
Ex: Write a program in C to input two value & find out the largest element using
pointer.
#include<stdio.h>
void main()
{
int x, y, *p1,*p2;
clrscr();
printf(“Input value of x & y”);
scanf(“%d%d”,&x,&y);
p1=&x;
p2=&y;
if(*p1>*p2)
{
printf(“%d is largest number”,*p1);
}
else
{
printf(“%d is largest number”,*p2);
}
getch();
}
NULL Pointer:
Null pointer is special pointer which does not point any valid memory address. It
is denoted by NULL keyword. It is available in stdio.h header file.
Some uses of the null pointer are:
a) To initialize a pointer variable when that pointer variable isn’t assigned any
valid memory address yet.
b) To pass a null pointer to a function argument when we don’t want to pass any
valid memory address.
Ex:
int *ptr=NULL;
Void Pointer or Generic Pointer:
“A void pointer is a pointer that has no associated data type with it. A void pointer
can hold address of any type and can be type casted to any type”. It is also called
general purpose pointer.
If we assign address of char data type to void pointer it will become char Pointer,
if int data type then int pointer and so on. Any pointer type is convertible to a void
pointer hence it can point to any value.
Declaration of void pointer:
void *var_name;
Ex:
#include<stdio.h>
int main()
{
int a = 10;
void *ptr = &a;
printf("%d", *(int
*)ptr); return 0;
}
Output: 10