3

I came across a code whoes output I'm not able to understand.The code is-

int main() 
{       
  int a[] = {1, 2, 3, 4, 5, 6};   

  int *ptr = (int*)(&a+1); 
  printf("%d ", *(ptr-1) ); 
  return 0; 
} 

The output of above code is coming out 6, but i think that it should be 1. Please explain why it is 6.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

4 Answers4

3

In your question "&a" is address of the whole array a[]. If we add 1 to &a, we get “base address of a[] + sizeof(a)”. And this value is typecasted to int *. So ptr points to the memory just after 6 . ptr is typecasted to "int *" and value of *(ptr-1) is printed. Since ptr points memory after 6,so ptr – 1 points to 6.

Deepak
  • 275
  • 2
  • 18
  • name of array in C gives the address(except in sizeof operator) of the first element. adding 1 to this address gives the address plus the sizeof type the array has – Deepak Jun 23 '15 at 21:33
  • that is second element – Deepak Jun 23 '15 at 21:33
  • @DeepakTiwari: There are more exceptions to automatically converting an array to a pointer. See [the standard](http://port70.net/~nsz/c/c11/n1570.html#6.3.2.1p3). That actually includes the reason you just gave in your answer. – too honest for this site Jun 23 '15 at 21:45
2

&a is an address of array a. Adding 1 to it will increment it to one past the array (adding 24-bytes). Cast operator (int*) cast &a+1 to pointer to int type. ptr-1 will decrement ptr by 4 bytes only and therefore it is the address of last element of array a. Dereferencing ptr - 1 will give the last element which is 6.

haccks
  • 104,019
  • 25
  • 176
  • 264
0

Yes, because a is an array having a type int[6]. Therefore, &a gives you the type int (*)[6]. It is not same as pointer to int, it is a pointer to int array.

So, &a + 1 increments the pointer by one of the the array size, pointing past the last element of the array.

Then, taking the address in ptr and doing a -1, decreases the address by a sizeof(*ptr) which is sizeof(int), which gives you the address of last element on the array.

Finally, de-referencing that address, you get the value of the last element , 6. Success.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

Because (int*)(&a + 1) uses the whole array as the base type and adds 1 whole size of an array to the address , i.e. adding 24 bytes.

And when you do ptr-1 since ptr type is int it will subtract only 4 bytes. Its very important to remember the type of the pointer while doing pointer arithmetic.

DollarAkshay
  • 2,063
  • 1
  • 21
  • 39