读书人

这是为什么?该如何处理

发布时间: 2012-03-14 12:01:12 作者: rapoo

这是为什么?
main()
{int a[5] = {1,2,3,4,5};
int *ptr = (int*)(&a+1);//关键在这,在我机器上运行,a的地址为0x12f450,(&a+1)为0x12f451,(int*)(&a+1)也为0x12f451,但这步执行过后,ptr为0x12f464
到底为什么啊!!!!

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

The output for this program is:

(a) 2 2

(b) 2 1

(c) 2 5

(d) None of the above

The answer is (c)
type of a is array of int

type of &a is pointer to array of int

Taking a pointer to the element one beyond the end of an array is sure to work.

我比较奇怪的是ptr的地址



[解决办法]
我的理解是这样的:
int *ptr = (int*)(&a+1);

a可以看成指向a[0]的指针,即存储的是a[0]的地址。

那么&a表示的是a这个指针的地址

&a+1是在a指针的地址+1得到的是【a指针所指内存空间下一地址】即a[4]后面的一个地址。

所以ptr-1就是a[4]的地址
[解决办法]
数组名就是数组0号元素的地址。
a = &a[0]
&a 是指向一个有5个整型元素的数组的地址。 a是一维指针,&a相当于是二维指针。 &a+1 就是从a向后跳过一个完整的数组所占用的内存空间。 整型5个元素的数组占用 5*sizeof(int)=5*4=20,所以 &a+1应该从a向后跳20字节。正好指到a[4]的后面。ptr是int *, 减1就是向前跳4个字节,ptr-1正好指向a[4]

读书人网 >C语言

热点推荐