Kumar Gaurav
Kumar Gaurav

Reputation: 939

2D array in C with pointer

I am trying to understand below code output:

int counter = 0; 
int aMatrix[5][5]; 
register int *aPtr; 
int i, j; 
for (i=0; i<5; i++) 
for (j=0; j<5; j++) 
aMatrix[i][j] = counter++; 
aPtr = &aMatrix[1][1]; printf("%d\n", aPtr[2]);

Referring to the sample code above, what will be the value of "aPtr[2]", after execution?

please help me to understand why I am getting 8 as output.

Upvotes: 0

Views: 93

Answers (3)

macfij
macfij

Reputation: 3209

i'd like to add that the multidimensional arrays are stored contiguously in memory. statement

int aMatrix[5][5];

is evaluated by compiler to

int (*aMatrix)[5];

so it is a pointer to 5 element array of ints. that's the size of your column. C doesn't check for boundaries and compiler doesn't know that there are 5 rows in your matrix.
furthermore, statement

aPtr = &aMatrix[1][1];

is evaluated to

aPtr = &(*(*(aMatrix + 1) + 1));

so it takes the address of aMatrix, by adding 1 it really adds 5, because aMatrix points to 5 ints. then, it is dereferenced and now just 1 is added. then, another dereference and aPtr points to address of that cell.
aPtr points to one int. so aPtr[2] adds 2. to sum up, 5+1+2 = 8.

what aMatrix really look like is

aMatrix ---> [0 1 2 3 4] [5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19] [20 21 22 23 24]
              ^                      |______________|
           aMatrix[0][0]                aMatrix[2]

you could get the same output by, for instance, writing following code:

int* testPtr = &aMatrix[0][0];
printf("%d\n",testPtr[8]);

Upvotes: 0

Sathish
Sathish

Reputation: 3870

for (i=0; i<5; i++) 
for (j=0; j<5; j++) 
aMatrix[i][j] = counter++;

After the execution of for loop your aMatrix contains-

aMatrix[0] --> 0  1  2  3  4 
aMatrix[1] --> 5  6  7  8  9
aMatrix[2] --> 10 11 12 13 14
aMatrix[3] --> 15 16 17 18 19
aMatrix[4] --> 20 21 22 23 24

So aMatrix[1][1] contains 6, you are assigning the address of aMatrix[1][1] to aPtr. That is aPtr[0] = 6, aPtr[1] = 7 and aPtr[2] = 8. So Obviously you will get output 8.

Upvotes: 1

Yu Hao
Yu Hao

Reputation: 122363

After the assignment, the matrix becomes:

0 1 2 3 4
5 6 7 8 9
...

With

aPtr = &aMatrix[1][1];

aPtr[0] is the same as aMatrix[1][1], so aPtr[2] is the same as aMatrix[1][3], which is 8 in the matrix.

Upvotes: 5

Related Questions