2
#include<cstdio>
int main() {

int a[5] = {1,2,3,4,5};

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

printf("%d %d" ,*(a+1),*(ptr-1));
}

here there the address location of a+1 is typecasted to point ptr;

i have tried ptr = (int)&a it is pointing the array.. as pointer address is stored in some location pointer ptr is pointing to that location how it is able to reference the location of array elements using *ptr

the output of the program is 2 5 can you please explain how 5 is the output

3 Answers3

2

Since a is an array of 5 ints, &a is a pointer to an array of 5 ints. Because pointer arithmetic operates on multiples of the size of the pointed type, &a+1 is a pointer to a fictional array of 5 ints right after the ints stored in a. When you cast that to pointer to int and store in ptr you get a pointer to the first int in that array.

In other words,

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

is equivalent to

int *ptr = (a + 5);

and this makes *(ptr-1) the same as *(a+4), which is the same as a[4], the last element of a.

Joni
  • 108,737
  • 14
  • 143
  • 193
0

The name of the array is the address. So &a and a have same value. &a evaluates to the same address and it creates a pointer of the type int(*)[size] which is a pointer to an array, not to a single element. If you increment this pointer, it'll add the size of the entire array, not the size of a single element.

Vivek Sadh
  • 4,230
  • 3
  • 32
  • 49
-1

int * ptr = &a[0]; ptr now points the first element of the array (1) ptr + 1 points to the 2, etc.

Dale Wilson
  • 9,166
  • 3
  • 34
  • 52
  • there is difference between (&a+1) and &a[1]; – rsaisankalp Jul 15 '13 at 17:39
  • -1, missing the point. `ptr+1` points to one after `ptr`, but that's one element. And the element here is `int[5]`. – MSalters Jul 15 '13 at 21:00
  • You are correct. The real point of my answer should be "Don't do that." and I was trying to show a better way to attach a pointer to an array. Actually int * ptr = a; and int * ptr=&a[0]; produce identical results, but I have seen a lot of developers confused by the first one (including the poster of this question.) – Dale Wilson Jul 19 '13 at 17:31
  • The cast in the OP's code is incorrect. He is changing the type of the pointed-to object from int[5] to int. Adding 1 to int[5]* points to an address beyond the array. Adding one to int * points to the next element of the array. – Dale Wilson Jul 19 '13 at 17:33