edited by
1,289 views
8 votes
8 votes

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
edited by

2 Answers

4 votes
4 votes
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.
0 votes
0 votes

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

Answer:

Related questions

4 votes
4 votes
2 answers
1
6 votes
6 votes
2 answers
2
Arjun asked Oct 18, 2016
628 views
What is the output of this program?#include <stdio.h int main() { char *ptr; char string[] = "Hello 2017"; ptr = string; ptr += 4; printf("%s",++ptr); }Hello 2017ello 201...
3 votes
3 votes
2 answers
4