816 views

2 Answers

6 votes
6 votes

Let's calculate (*(*(*p)[1] - 2)) 

Assume arr is stored at address 100.
p = &arr,
p points to location 100 and type is pointer to array[2][3][3] of char.

Let's calculate (*p)[1]:
Since p points to address 100, *p would point to address 100 too (but scale differently).
Let p1 = *p, so above expression becomes:
(*(*p1[1] - 2))

p1 points to address 100 and has type pointer to array[3][3] of char.
p1[1]
== p1 + 1 * sizeof(*p1)
== p1 + 1 * sizeof(char[3][3])
== p1 + 9
== 109.

Let p2 = p1[1], so above expression becomes:
(*(*p2 - 2))
After removing the redundant paranthesis it is:
*(*p2 - 2)
where p2 points to 109 and has type pointer to array[3] of char.

Let p3 = *p2, ie p3 points to location 109 and has type pointer to char.
The above expression becomes:
*(p3 - 2)

p3 - 2
== p3 - 2 * sizeof(*p3)
== p3 - 2 * sizeof(char)
== p3 - 2 * 1
== p3 - 2

Since p3 points to location 109, p3 - 2 would end up being location 107.
Hence *(p3 - 2) would be value at location 107, ie, at 7 bytes from arr which equals 'E'.

So the value of the expression: (*(*(*p)[1] - 2)) would be 'E'.

Similarly value of the expression (*(*(*p[0] + 1)) would be 'A'.

'E' - 'A' == 69 - 65 == 4.

Hence the output should be 4

5 votes
5 votes
#include <stdio.h>
int main() {
  char arr[2][3][3] = {'R','A','U','D','R','A',' ','E','D','U'};

  // This above array is nothing but a contiguous storage of bytes
  // where initial 10 locations are initialized and others are not
  char *c = **arr; // because array decays to the first element type of address
  int i;
  for(int i=0;i<10;i++) printf("%c ",*(c+i));
  printf("\n");
  // ok !!

  // Now,
  char (*p)[2][3][3] = &arr;

  // we know for any pointer ptr : 
  // ptr + k = ptr + k*sizeof(*ptr)
  // if we use TYPE (*ptr)[m][n][p]...[q] = &arr 
  // where TYPE arr[m][n][p]...[q] already declared
  
  // &arr : this pointer has a type == pointer to an array of m*n*p*..*q D array of TYPE
  // note that &arr is not decaying to the pointer of the first element of arr.
  // then ptr + k = ptr + k * ( (m*n*p...*q) * sizeof(TYPE) )

  printf("%d\n",(*(*(*p)[1] -2)) - (*(*(*p)[0] +1)) );
  
  // answer is 4
  // following image is added to visualize the pointer arithmetic

  return 0;
}
// output:
R A U D R A   E D U 
4

Related questions

0 votes
0 votes
1 answer
1
shivam sharma 5 asked Aug 28, 2018
549 views
give the complete solution with explanationint main(){ int arr = {10,2,3,4,5,6,7,8}; int *p, *q; p = &arr ; q = (int*) arr; printf("%d ,%d \n",*p...
0 votes
0 votes
4 answers
4
Ismail asked Apr 5, 2018
1,594 views
What will the following code fragment output: void fun(int *a, int b) { b++; a = a + 3; } void main() { int A[5] = {0,1,2,3,4}; fun(A, A ); printf(%d, A ); }