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

2
  • Nowhere do you have a pointer to a pointer. Commented Jul 15, 2013 at 17:37
  • As for why &a doesn't return a pointer to a pointer, see e.g this old question. Commented Jul 15, 2013 at 17:38

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

-1

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

4 Comments

there is difference between (&a+1) and &a[1];
-1, missing the point. ptr+1 points to one after ptr, but that's one element. And the element here is int[5].
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.)
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.