825 views

Consider the following C function:

void foo()
{
int a[10][20][30] = {0};
__________
printf("%d", a[3][4][5]);
}

Which of the following could be used in the missing line so that the output is 2?

1. a[3][4][5] = 2;
2. *(*(*(a+3) + 4) + 5) = 2;
3. (*(*(a+3) + 4))[5] = 2;
4. *((int*)a + 3 * 20 * 30 + 4 * 30 + 5) = 2;
1. Only 1 and 2
2. Only 1, 2 and 3
3. Only 1
4. 1, 2, 3 and 4

a[3][4][5]
*(*(*(a+3) + 4) + 5)
(*(*(a+3) + 4))[5]
*((int*)a + 3 * 20 * 30 + 4 * 30 + 5)

All four are same expression.

Thanx sir got the point. In case of one d array it will work even without typecasting because the name of array itself will return an integer pointer.?
yes.. As I told this rule works for any data type - all we need to know is the type and its size.

@ sir,

If we remove (int*) , now  a  acts as pointer to 1st  2D array and here a + 3 * (..)  ==> a + 3 *(Sizer of 2D array)

*(a + 3 * 20 * 30 + 4 * 30 + 5)

Am i right sir ??

For a single dimensional array a

Address of the first element = &a[0] = a

Value in the first element = a[0] = *a

This can be extended to any number of dimensions.

1. is clear.

2. *(*(*(a+3) + 4) + 5)
*(*(a[3] + 4) + 5)
*( a[3] [4]) + 5)
a[3] [4] [5]

3. See 2.

4. Assuming the array is stored in RMO (default in C)
*((int*)a + 3 * 20 * 30 + 4 * 30 + 5)
Recall how we calculate the address of an index[i,j]? By skipping i rows and j columns from base address.
=> By skipping (i * size of row) elements + j elements from base address
=> base address + ((i * size of row) + j) elements

The same is being done here for three dimensional arrays, which gives the element at a[3][4][5]

Hence, Option D