Pointers in C Questions and Answers
Last Updated on September 26, 2016 by Jhasketan Garud
Pointers in C Questions and Answers
These questions and answers in Pointers in C have been prepared to help you in interviews and exams.
Q1. Combine the following two statements into one?
char *p; p = (char*) malloc (100) ;
Answer :
char *p = (char*) malloc (100);
Note that the tpecasting operation can be dropped completely if this program is built using gcc compiler.
Q2. Are the expressions *ptr++ and ++*ptr same?
Answer :
No. *ptr++ increments the pointer and not the value pointed by it, whereas ++*ptr increments the value being pointed to by ptr.
++*ptr works like *ptr = *ptr+1
Q3. Can you write another expression which does the same job as ++*ptr ?
Answer :
(*ptr)++
Q4. What would be the equivalent pointer expression for referring the array element a[i][j][k][l] ?
Answer :
*(*(*(*(a+i)+j)+k)+l)
Q5. If the size of an integer is 4 bytes what will be the output of the following program?
#include <stdio.h>
int main()
{
int arr[] = {12, 13, 14, 15, 16};
printf ("%d %d %d\n", sizeof (arr), sizeof (*arr), size of (arr[0]));
}
Answer :
20 4 4
Q6. What will be the output of the following program assuming that the array begins at location 1002 and size of an integer is 4 bytes?
#include <stdio.h>
int main()
{
int a[3][4] = {
1,2,3,4,
5,6,7,8,
9,10,11,12
};
printf ("%u%u%u\n", a[0]+1,*(a[0]+1),*(*(a+0)+1));
return 0;
}
Answer :
1006 2 2
Q7. Will the following program compile?
#include <stdio.h>
int main()
{
char str[5] = "fast enough";
return 0;
}
Answer :
Yes. The compiler never detects the error if bounds of an array are exceeded.
Q8. Which of the following is the correct output for the program given below?
#include <stdio.h>
int main()
{
int arr[3] = {2,3,4};
char*p;
p=(char*)arr;
printf ("%d",*p);
p=p+1;
printf ("%d\n",*p);
return 0;
}
A. 2 3
B. 2 0
C. 1 0
D. Garbage values
Answer : B
Q9. Which of the following is the correct output of the program given below?
#include <stdio.h>
int main()
{
int arr[2][2][2] = {10,2,3,4,5,6,7,8};
int *p, *q;
p = &arr[1][1][1];
q = (int*) arr;
printf ("%d %d\n", *p, *q);
return 0;
}
A. 8 10
B. 10 2
C. 8 1
D. Garbage values
Answer : A
Q10. What will be the output of the following program assuming that the array begins at location 1002?
#include <stdio.h>
int main()
{
int a[2][3][4] = {
{
1,2,3,4,
5,6,7,8,
9,1,1,2
},
{
2,1,4,7,
6,7,8,9,
0,0,0,0
}
};
printf ("%u %u %u %d\n", a, *a, **a, ***a);
return 0;
}
Answer:
1002 1002 1002 1