Outputting Code Behavior & in c

I stumbled upon a whoes output code that I cannot figure out. Code -

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

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

      

The output of the above code comes out 6, but I think it should be 1. Please explain why it is 6.

+3


source to share


4 answers


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



+3


source


&a

is the address of the array a

. Adding 1

to it will increase it to one per array (adding 24 bytes). Cast the rotation operator (int*)

to a &a+1

pointer to a type int

. ptr-1

will only decrease ptr

by 4

bytes and so this is the address of the last element of the array a

. Highlighting ptr - 1

will give the last item 6

.



+2


source


Yes, because it a

is an array of type int[6]

. Therefore &a

gives you the type int (*)[6]

. This is not the same as a pointer to int, it is a pointer to an array int

.

So, &a + 1

increments the pointer by one of the array sizes, pointing to the last element of the array.

Then, taking the address in ptr

and doing -1

, decrements the address by sizeof(*ptr)

which is equal sizeof(int)

, which gives you the address of the last element in the array.

Finally, remove the reference to this address, you get the value of the last element 6

. Success.

0


source


Since it (int*)(&a + 1)

uses the entire array as a base type and adds 1 full size of the array to it, that is, it adds 24 bytes.

And when you do ptr-1

, since ptr

type is int, it only subtracts 4 bytes. It is very important to remember the pointer type when doing pointer arithmetic.

0


source







All Articles