Saturday, June 17, 2023

C language - Pointer

POINTER

Pointer points address of another variable

Use:

To store and manage the addresses of dynamically allocated blocks of memory 

syntax

datatype  *variablename=value;

eg. int  *a=5;

int *b=&a; 


program1

#include<stdio.h>

#include<conio.h>

main()

{

int a,*ptr;

ptr=&a;

printf("the value of a= %d\n",a);

printf("the value of &a= %u\n",&a);

printf("the value ptr= %u\n",ptr);

printf("the value *ptr= %d\n",*ptr);

a=10;

printf("the value of a= %d\n",a);

printf("the value of &a= %u\n",&a);

printf("the value ptr= %u\n",ptr);

printf("the value *ptr= %d\n",*ptr);

getch();

}

output:

the value of a= -3483

the value of &a= 3042

the value of ptr= 3042

the value of *ptr=-3483

the value of a = 10

the value of &a= 3042

the value of ptr= 3042

the value of *ptr=10

Int and float storage in pointer

Int

Byte value -2

5

 

8

 

9

 

3

 

6

 

1000

1001

1002

1003

1004

1005

1006

1007

1008

 

Float

Byte value -4

5.5

 

 

 

9.2

 

 

 

6.7

 

1000

1001

1002

1003

1004

1005

1006

1007

1008

 

 

program 2

#include<stdio.h>

#include<conio.h>

main()

{

int  a,*ptri;

float b,*ptrf;

clrscr();

ptri=&a;

ptrf=&b;

printf("address of int pointer= %u\n",ptri);

ptri++;

printf("address of int pointer= %u\n",ptri);

printf("address of float pointer= %u\n",ptrf);

ptrf++;

printf("address of float pointer= %u\n",ptrf);

getch();

}

output:

address of int pointer = 22026

address of int pointer = 22028

address of float pointer = 22046

address of float pointer = 22050

program3:

#include<stdio.h>

#include<conio.h>

main()

{

char a[ ] = "hello from pointer";

char ptr = "hello from pointer";

printf("string using array =%s\n",a);

printf("string using pointer =%s\n",ptr);

getch();

}

output:

hello from pointer

hello from pointer

program:

#include<stdio.h>

#include<conio.h>

main()

{

int a[] ={0,1,2,3,4,5,6,7,8,9};

int i,*ptr;

ptr=a;

for(i=0;i<=9;i++)

{

printf("address =%u value=%d\n",ptr, *ptr);

ptr++;

}

getch();

}

output:

address=22046 value=0

address=22048 value=1

address=22050 value=2

address=22052 value=3

address=22054 value=4

address=22056 value=5

address=22058 value=6

address=22060 value=7

address=22062 value=8

address=22064 value=9

pointer arithemetic:

int*ptr;

*ptr=2;

ptr+1;

Pointer to Function (Swapping Program)

 

a=10      b=20

 

a=20       b=10

program:

#include<stdio.h>

#include<conio.h>

void swap(int  *x,int  *y)

{

int c;

c=*x;

*x=*y;

*y=c;

}

main()

{

int a,b;

clrscr();

printf("enter a,b\n");

scanf("%d%d",&a,&b);

printf("before swapping a=%d b=%d\n",a,b);

swap(&a,&b);

printf("after swapping a=%d b=%d\n",a,b);

getch();

}

output

before swapping a=10  b=20

after  swapping   a=20  b=10

 

0 comments:

Post a Comment