首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

a[1]与&a[1]?该怎么解决

2012-02-21 
a[1]与&a[1]?inta[3][5]int(*p)[5]pa[1]//警告p&a[1]//正确printf( %x,%x ,a[1],&a[1])//其实结

a[1]与&a[1]?
int   a[3][5];  
int   (*p)[5];  

p=a[1];//警告  

p=&a[1];//正确  

printf( "%x,%x ",a[1],&a[1]);//其实结果是一样的  

a[1]与&a[1]是什么关系?

[解决办法]
楼主可以看《C primer plus》第10章,有一节是专门讲多维数组与指针的。

int zippo[4][2]; /* an array of arrays of ints */

Then zippo, being the name of an array, is the address of the first element of the array. In this case, the first element of zippo is itself an array of two ints, so zippo is the address of an array of two ints. Let 's analyze that further in terms of pointer properties:

Because zippo is the address of the array 's first element, zippo has the same value as &zippo[0]. Next, zippo[0] is itself an array of two integers, so zippo[0] has the same value as &zippo[0][0], the address of its first element, an int. In short, zippo[0] is the address of an int-sized object, and zippo is the address of a two-int-sized object. Because both the integer and the array of two integers begin at the same location, both zippo and zippo[0] have the same numeric value.

Adding 1 to a pointer or address yields a value larger by the size of the referred-to object. In this respect, zippo and zippo[0] differ, because zippo refers to an object two ints in size, and zippo[0] refers to an object one int in size. Therefore, zippo + 1 has a different value from zippo[0] + 1.

Dereferencing a pointer or an address (applying the * operator or else the [ ] operator with an index) yields the value represented by the referred-to object. Because zippo[0] is the address of its first element, (zippo[0][0]), *(zippo[0]) represents the value stored in zippo[0][0], an int value. Similarly, *zippo represents the value of its first element, zippo[0], but zippo[0] itself is the address of an int. It 's the address &zippo[0][0], so *zippo is &zippo[0][0]. Applying the dereferencing operator to both expressions implies that **zippo equals *&zippo[0][0], which reduces to zippo[0][0], an int. In short, zippo is the address of an address and must be dereferenced twice to get an ordinary value. An address of an address or a pointer of a pointer is an example of double indirection.


[解决办法]
给楼主举个1维数组的例子,2维就自然明白了。

int a[4];
此时a和&a都表示数组a的起始地址,之所以如此,是因为编译器知道a是一个数组名字,所以它故意让&a也返回数组的起始地址(而数组名字a本来就表示数组起始地址,所以不用多说)。

再看看这个:
int *a = new int[4];
现在a和&a就不同了,a是动态分配数组的起始地址,而&a是指针a的地址,为什么此处编译器不将&a也理解为动态分配数组的起始地址呢?因为此时编译器看到的是“int *”,所以它只知道a是一个指针,不认为它是一个数组。

大概就是这样。

热点排行