0
What is the output of following code? Explain output
#include<stdio.h> int main(){ int a[][3]={1,2,3,4,5,6}; int(*ptr)[3]=a; printf("%d %d",(*ptr)[1],(*ptr)[2]); ++ptr; printf("%d %d",(*ptr)[1],(*ptr)[2]); }
3 Answers
+ 3
int [][3]a= {1,2,3,4,5,6};
Here a[0] = {1,2,3}, a[1] ={4,5,6};
int (*ptr) [3] = a ;
Means a[0] address pointed by ptr, and
(*ptr)[0] = 1, (*ptr)[1] = 2, (*ptr)[2]=3;
ptr++; now ptr points to a[1][0]
(*ptr) [0] =4, (*ptr) [1] = 5, (*ptr) [2] = 6..
So first printf output is 2,3
Second printf output is 5,6
Note :
Arrays are stored in continues locations of memory....
So
a[][3] will store max column index is 2, can store 3 values max.
so
a[0][0] = 1,
a[0][1] = 2,
a[0][2] = 3.
Similarly
a[1][0] = 4, a[1][1] =5, a[1][2] =6.
ptr++ will point to next row of 'a' that is a[1]
a[0] will point to a[0][0] and *a[0] same as a[0][0], and returns 1.
a[1] is point to a[1][0] and *a[0] same as a[1][0].
Hope it helps...
0
Tq u
0
Edit :
Ayesha
You're welcome...