II-212 Programming Concepts
17. Use pointers to pointers and display numbers
#include <stdio.h>
#include <stdio.h>
#include <conio.h>
void main()
{
int k;
int a[]={1,2,3};
int *b[3];
int **c[3];
int ***d[3];
int ****e[3];
int *****f[3];
clrscr();
for(k=0;k<3;k++)
{
b[k]=a+k;
c[k]=b+k;
d[k]=c+k;
e[k]=d+k;
f[k]=e+k;
}
for(k=0;k<3;k++)
{
printf("%3d",*b[k]);
printf("%3d",**c[k]);
printf("%3d",***d[k]);
printf("%3d",****e[k]);
printf("%3d ",*****f[k]);
}
}
OUTPUT:
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
M09_ITL-ESL4791_02_SE_C09.indd 212 12/22/2012 5:04:03 PM
Pointers II-213
Find the bug/s in the following programs.
1.
#include <stdio.h>
void main()
{
char *c;
float x=10;
c=&x;
printf("%d",*c);
}
Bug: Pointer and variable it pointing to should be
of same type
2.
#include <stdio.h>
void main()
{
float x=10.25,*f;f=x;
clrscr();
printf("%g",*f);
}
Bug: & is missing in assignment statement
3.
#include <stdio.h>
void main()
{
float x=10.25,*t,*f;
t=&x;
f=&t;
clrscr();
printf("%g",**f);
}
Bug: **f should be declared as pointer of pointer
4.
#include <stdio.h>
void main()
{
char sa[]="How are you ?";
char t,*f;f=&sa;
M09_ITL-ESL4791_02_SE_C09.indd 213 12/22/2012 5:04:03 PM
II-214 Programming Concepts
clrscr();
printf("%s",f);
}
Bug: & is not needed
5.
#include <stdio.h>
void main()
{int *t,x;t=&x;x=11;
*t++;
clrscr();
printf("%d",*t);
}
Bug: *t++; does not work. It must be ++*t;.
With this change this answer will be 12.
6.
#include <stdio.h>
void main()
{
int t[]={1,2,3,4,5};
int *p,*q,*r;p=t;q=p[1];
r=p[2];
clrscr();
printf("%d %d %d",*p,*q,*r);
}
Bug: & is required in q=p[1]; and r=p[2];
7.
#include <stdio.h>
void main()
{
int num[2][3]={1,2,3,4,5},*k;
k=&num;
clrscr();
printf("%d",*k);
}
Bug: k=&num; should be k=&num[0][0];
M09_ITL-ESL4791_02_SE_C09.indd 214 12/22/2012 5:04:03 PM
Pointers II-215
8.
#include <stdio.h>
void main()
{
int x=5,y=8,z;
int *px,*py,*pz;px=&x;py=&y;pz=&z;pz=*px+*py;
clrscr();
printf("%d",z);
}
Bug: In the assignment statement *pz required
9.
#include <stdio.h>
void main()
{
int x=5;
int *px=&x,*py;
clrscr();
printf("%d",px);
}
Bug: %u is required for formatting address
10.
#include <stdio.h>
void main()
{
int x,*px;
*px=5;
px=&x;
clrscr();
printf("%d",x);
}
Bug: The statement *px=5; should appear after px=&x;
11.
#include <stdio.h>
#include <conio.h>
void void main()
{
int *p,*q,a=2;
p=&a;
q=p;
M09_ITL-ESL4791_02_SE_C09.indd 215 12/22/2012 5:04:03 PM
II-216 Programming Concepts
clrscr();
printf("%d %d", p ,q);
}
Bug: * is missing (*p,*q)
M09_ITL-ESL4791_02_SE_C09.indd 216 12/22/2012 5:04:03 PM
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset