Concept of Pointer In C

A pointer is a variable that stores the address of another variable is called a pointer.

Syntax – Data Type *pointer name;

Two types of the operator are used in the program of the pointer.

  1.  Address Operator(&) – This operator can’t be used in any constant or expression. 
  2. Dereference Operator or indirection(*) – This operator gives the value stored at that particular address.

1.  Program to check the size of the pointer by using sizeof operator. 

#include<stdio.h>
#include<conio.h>

void main()
{
clrscr();

printf("int size %d \n",sizeof(int));
printf("int pointer size %d \n",sizeof(int *));

printf("char size %d \n",sizeof(char));
printf("char pointer size %d \n",sizeof(char *));
getch();

Output:
int size 2
int pointer size 2
char size 1
char pointer size 2

2. Program to understand more clearly about pointer-

#include<stdio.h>
#include<conio.h>


void main()
{
int n=10,*ptr;
clrscr();

ptr=&n;

printf("%d\n",n);
printf("%u\n",ptr);
printf("%d\n",*ptr);
ptr++;
printf("%u\n",ptr);
printf("%d\n",*ptr);
ptr--;
printf("%d\n",*ptr);
*ptr=*ptr*10;
printf("%d\n",*ptr);
printf("%d\n",n);

getch();
}
Output:
10
65524
10
65526
0
10
100
100

3. Addition of two values using a pointer :

#include<stdio.h>
#include<conio.h>


void main()
{
int a,b,c,*p1,*p2,*p3;
clrscr();
p1=&a;
p2=&b;
p3=&c;

printf("enter the value of A and B");
scanf("%d%d",&a,&b);
*p3=*p1+*p2;

printf("%d",*p3);
getch();
}
Output:
enter the value of A and B12
12
24

4. Array Pointer in C –

#include<stdio.h>
#include<conio.h>


void main()
{
int x[5],*ptr,i;
clrscr();

ptr=&x[0];

printf("enter the data");
for(i=0;i<5;i++)
{
scanf("%d",ptr);
ptr++;
}
ptr=&x[0];
printf("array data are");
for(i=0;i<5;i++)
{		
printf("%d\n",*ptr);
ptr++;
}
getch();
}

Output:
enter the data1
2
3
4
5
array data are1
2
3
4
5

5. Call By value: In simple words, there is no change in the original.

#include<stdio.h>
#include<conio.h>

void swap(int ,int );
void main()
{
int a,b;
clrscr();
printf("enter the value of A and B");
scanf("%d%d",&a,&b);
printf("before\n");
printf("%d\n%d\n",a,b);
swap(a,b);
printf("after\n");
printf("%d\n%d\n",a,b);

getch();
}
void swap(int x,int y)
{
int temp=x;
x=y;
y=temp;
printf("swap\n");
printf("%d\n%d\n",x,y);
}

Output:
enter the value of A and B12
13
before
12
13
swap
13
12
after
12
13

6. Call By Reference: There is a change in the original.

#include<stdio.h>
#include<conio.h>

void swap(int *,int *);
void main()
{
int a,b;
clrscr();
printf("enter the value of A and B");
scanf("%d%d",&a,&b);
printf("before\n");
printf("%d\n%d\n",a,b);
swap(&a,&b);
printf("after\n");
printf("%d\n%d\n",a,b);

getch();
}
void swap(int *x,int *y)
{
int temp=*x;
*x=*y;
*y=temp;
printf("swap\n");
printf("%d\n%d\n",*x,*y);
}

Output:
enter the value of A and B12 
13
before
12
13
swap
13
12
after
13
12

 

Leave a Reply