1
int arr[3][2]={{1,2},{3,6},{8,6}};
printf("%d %d %d",arr[0][3],arr[1][2],arr[2][0]);

output of this program is coming as 6 8 8 can someone please explain me how is this happening

1
  • Basically this is the same as asking "what day of the week is the 31st of November?" and the compiler assumes you mean the 1st of Decemeber. Don't do that; it's confusing and error-prone. Commented Mar 12, 2014 at 18:23

3 Answers 3

2

The values {{1,2},{3,6},{8,6}}; are stored in the consecutive memory location.

Assume this way:

Let say arr location is : 100, size of integer is 4

Location 100   : 1

Location 104   : 2

Location 108   : 3

Location 112   : 6

Location 116   : 8

Location 118   : 6

When you are accessing

   arr[0][3] =  arr[0] = 100. arr[0][3] = 100 + (3*4) = 112 location Ie: value 6.
   arr[1][2] =  arr[1] = 108. arr[1][2]  = 108 + (2*4 ) = 116 loation Ie: value 8.
   arr[2][0] =  arr[2] = 116. arr[2][0]  = 116 + 0 = 116 location. Ie: value 8.

Hence it get printed 6, 8, 8.

Hope it helps.

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

Comments

1

Your second dimension has only 2 items; thus, the only valid indices are 0 and 1. But C is forgiving (stupid?) enough to compute where that element WOULD be if that row were long enough; so [0][3] maps to [1][1] (the 6), and [1][2] maps to [2][0] (the 8).

Comments

1

a[0] will be pointing at a+0 i.e at 1(a[0][0]) so now adding 3 from there will be resulting in moving arr to 6.
now a[1][2], a[1] points at '3'(a[1][0]) so adding 2 to it results in arr pointing to 8.
similary for a[2][0], a[2] will be pointing at '8' (a[2][0]).
This result is because the numbers in this array is stored in memory continuously row by row.

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.