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

4

3 回答 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.

于 2013-07-15T17:39:38.297 回答
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.

于 2013-07-15T17:39:36.967 回答
-1

int * ptr = &a[0]; ptr 现在指向数组的第一个元素 (1) ptr + 1 指向 2,依此类推。

于 2013-07-15T17:36:28.370 回答