Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

pointers

#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 'm getting 5 .. Why ?

like image 459
Yogeesh Seralathan Avatar asked Feb 28 '13 17:02

Yogeesh Seralathan


3 Answers

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

The address of the array is taken, and then 1 is added to it, which produces a pointer pointing sizeof a bytes past the beginning of a. That pointer is then cast to an int*, and that is assigned to ptr. The same could be achieved with

int *ptr = &a[5];

in this case.

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

Pointer arithmetic is done in units of "size of pointee". Since &a is a pointer to an array of 5 int - an int (*)[5], adding 1 to it moves it 5*sizeof(int) bytes.

like image 156
Daniel Fischer Avatar answered Sep 20 '22 13:09

Daniel Fischer


&a is a pointer to pointer to int[5] and thus &a + 1 is again a pointer to int[5]. Loose the & and all should be fine(and also you will no longer need the cast):

int *ptr = a + 1;
like image 29
Ivaylo Strandjev Avatar answered Sep 18 '22 13:09

Ivaylo Strandjev


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

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

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

like image 21
Nguyen Thanh Ho Avatar answered Sep 22 '22 13:09

Nguyen Thanh Ho