Int * ptr = (int *) (& a + 1);

#include <stdio.h> int main(void) { int a[5] = { 1, 2, 3, 4, 5 }; int *ptr = (int*)(&a + 1); // what happens here ? printf("%d %d\n", *(a + 1), *(ptr - 1)); return 0; } 

I expected the answer to be 1, but I get 5. Why?

+4
source share
3 answers
 int *ptr = (int*)(&a + 1); // what happen here ? 

The address of the array is taken, and then 1 is added, which creates a pointer indicating sizeof a bytes at the beginning of a . This pointer is then transferred to int* and assigned to ptr . The same could be done with

 int *ptr = &a[5]; 

in this case.

Then ptr - 1 is a pointer indicating sizeof(int) bytes before ptr , that is, to &a[4] , and *(ptr - 1) is a[4] .

Arithmetic of the pointer is performed in units of "point size". Since &a is a pointer to an array of 5 int - an int (*)[5] , adding 1 to it moves its 5*sizeof(int) bytes.

+9
source

&a is a pointer to a pointer to int[5] and therefore &a + 1 again a pointer to int[5] . Free & , and everything should be fine (and you won’t need to throw anymore):

 int *ptr = a + 1; 
+5
source
 int *ptr = (int*)(&a + 1); // what happen here ? 

a = address of the first element of the array: a [0] (address int)

& a = array address a, same value with "a", but type is the address of the array, so the expression "(& a + 1)" is a pointer to the next array "a". (ptr - 1): pointer to the previous int ptr, which means the pointer to the last element of the array "a".

+1
source

All Articles