0

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.

1

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1
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.

Comments

0

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]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.