14.4 – Practicing dereferencing

by subbu on January 17, 2014

So far, we have learned how a memory allocation can be accessed through its pointer using dereference or indirect reference.

In this session let us practice some programs to master pointer and dereference. In all the programs we will create pointers to every variable and access them with pointers using indirection

Specification: Accept two numbers and print the sum of them

#include <stdio.h>
int main()
{
short x,y,z;      /*declaration of variables */
short *p,*q,*r; /* declaration of pointers */
p=&x;              /* assigning the addresses to the pointers */
q=&y;
r=&z;
printf("enter two integers:\n");
/* scanf("%d%d",&x,&y); */
scanf("%d%d",p,q);                  /* equal to &x and &y */
*r=*p+*q;
printf("Sum of two numbers %d",*r);
return 0;
}

Execution:
Enter two integers:
34
56
Sum of two numbers 90

Sum of two numbers

Here p, q and r are the pointers to the variables x, y and z. By using the value at operator * we can access the values of x, y and z

In the above program variables declaration, pointer declaration and pointer assigning statements are written as separate statements. We can minimize the code as

short x,y,z,*p,*q,*r;
p=&x;
q=&y;
r=&z;

Same code can be written as

short x,y,z,*p=&x,*q=&y,*r=&z;

Specification: Accept the length, breadth of a rectangle and print the area, perimeter

#include <stdio.h>
int main()
{
short l,b,area,peri,*x=&l,*y=&b,*a=&area,*p=&peri;
printf("Length:");
/* scanf("%d",&l); */
scanf("%d",x);
printf("Breadth:");
/* scanf("%d",&b);  */
scanf("%d",y);
*a=(*x)*(*y);
*p=2*(*x+*y);
printf("Area of rectangle %d",*a);
printf("\nPerimeter of rectangle %d",*p);
return 0;
}

Execution:
Length:25
Breadth:12
Area of rectangle 300
Perimeter of rectangle 74

Rectangle

Specification: Accept two numbers and print their values by interchanging them (Swapping)

#include <stdio.h>
int main()
{
short a,b,*p=&a,*q=&b;
printf("First number:");
/* scanf("%d",&a); */
scanf("%d",p);
printf("Second number:");
/* scanf("%d",&b); */
scanf("%d",q);
*p=*p+*q;
*q=*p-*q;
*p=*p-*q;
printf("First number %d",*p);
printf("\nSecond number %d",*q);
return 0;
}

Execution:
First number:34
Second number:45
First number 45
Second number 34

Swapping two numbers

Specification: Accept the radios of a circle and print the area, circumference

#include<stdio.h>
#include<math.h>
#define PI 3.14
int main()
{
short rad,*r=&rad;
float area,cir,*a=&area,*c=&cir;
printf("Radios of circle:");
scanf("%d",r);
*a=PI*pow(*r,2);
*c=2*PI*(*r);
printf("Area of circle %f",*a);
printf("\ncircumference of circle %f",*c);
return 0;
}

Execution:
Radios of circle:17
Area of circle 907.460022
Circumference of circle 106.760002

Circle

Previous post:

Next post: