C Programming Reference >> C Programming Reference Question Bank >>
19/07/07 - Views - Ratings :    4.09 of 5 / 11 Votes
Level - Intermediate
Question -
What will be the output of the following code?
#include <stdio.h>
int main()
{
int a[][3] = { 1,2,3 ,4,5,6};
int (*ptr)[3] =a;
printf("%d\n\n %d " ,(*ptr)[1], (*ptr)[2] );
++ptr;
printf("\n\n%d\n\n%d" ,(*ptr)[1], (*ptr)[2] );
return 0;
}
|
Answer -
2
3
5
6
Explanation -
Well this output can be easily expained on applying the fundamentals of c programming.
In statement -
int (*ptr) [3] = a ;
We are just declaring a int array of size 3 whose base address is address of array 'a'. So ptr [0] will be equal to a[0] and ptr[1] will be equal to a[1] and finally a[2] will be equal to ptr[2], so in first printf statement we are able to produce output 2 and 3.
Now when following statement execute -
++ptr;
ptr is incremented by one and using normal pointer artihemetic it will jump by 3 integer size memmory locations so now ptr [0] will be pointing to a[3], ptr [1] to a[4] & ptr [2] to a[5].
Reader Comments -
| rafael
|
correction:
at first, the ptr[0] will point to a[0][0] hence, ptr[1] = a[0][1] nd so on..
after ++ptr ptr[1] = a[0][2] and so forth...
in memory, data is stored in row major not column major by default!!! u did the same mistake in one of the previous problems also...
|
| harini
|
then is the ans 2 3 3 4? pls tel the right ans clearly
|
| zum
|
can u plz update d explanation for d answers aftr u noe d correction coz ther r many who refer 2 d code n think dat itself is d right answer !
|
| Jiraya
|
The explaination given is absolutely correct ,no fault with it . @rafael : After ++ptr; ptr=a[1][0]; and ptr[1] = a[1][1];
|
| tuhin
|
finally a gate question came...
|
|