-4
#include<stdio.h>
int main(){
  int a1[]={6,7,8,18,34,67};
  int a2[]={23,56,28,24};
  int a3[]={-12,27,-31};
  int *y[]={a1,a2,a3};
  int **a= y;

  printf("%d\n",a[0][2]);
  printf("%d\n",*a[2]);
  printf("%d\n",*(++a[0]));
  printf("%d\n",*(++a)[0]);
  printf("%d\n",a[-1][1]);
  return 0;
}

When I run the above code output is 8,-12,7,23,8. But if i change the last 3 lines to

printf("%d\n",*(++a[2]));
printf("%d\n",*(++a)[1]);
printf("%d\n",a[-1][1]);

output is 8,-12,27,27,7. I'm unable to understand last printf statement. How does a[-1][something] is calculated ? And according to me *(++a)[1] should print 56 instead of 27 !

Prakhar
  • 52
  • 10
  • Regarding the negative index, see [Are negative array indexes allowed in C?](https://stackoverflow.com/questions/3473675/are-negative-array-indexes-allowed-in-c) – Galen Dec 08 '17 at 04:30
  • 1
    `a` isn't an array, it is a pointer. `a[-1]` is the same as `*(a - 1)` which is fine if `a` points into the middle of an array. And yesterday we had [even funnier examples](https://stackoverflow.com/questions/47683569/can-someone-please-explain-me-this-pointer-c-code) – Bo Persson Dec 08 '17 at 04:31
  • @Galen I have read it already. It says if negative index is their just go back in the array. But I am unable to apply it here. – Prakhar Dec 08 '17 at 04:35
  • @Prakhar `a` is a pointer to a pointer. As Bo pointed out, `a[-1]` is the same as `*(a - 1)`. Review pointer arithmetic. – Galen Dec 08 '17 at 04:37

2 Answers2

0

Pointers and array bases are in fact addresses in virtual memory. In C, they can be calculated into new addresses. Since the compiler knows the size of memory the pointer points to (e.g. int * points to 4 Bytes), a pointer +/- 1 means the address +/- the size (e.g. 4 Bytes for int).

The operator * means to get the value stored in the specified address.

Another trick here is the priorities of the operators. [] is calculated before ++.

If you understand what I mean above, your problem should be resolved.

Harvett
  • 178
  • 2
  • 8
0

according to me *(++a)[1] should print 56 instead of 27 !

++a increments a to the next int *, so after it pointed to y[0] equal to a1, it points to y[1] equal to a2. Then [1] in turn designates the next int * after y[1], i. e. y[2] equal to a3+1 (due to the preceding ++a[2]). Lastly, * designates the int which y[2] points to, i. e. a3[1] equal to 27.

Armali
  • 18,255
  • 14
  • 57
  • 171