不,你的代码没有任何问题。只是你的思路有些偏差...我越想越觉得这很难解释,所以在我开始之前,请记住以下几点:
- 数组不是指针,不要将它们视为同一类型。
- []是一个运算符。它是一个移位和引用运算符,因此当我写
printf("%d",array[3]);
时,我正在进行移位和引用操作。
因此,一个数组(让我们首先考虑一维数组)存储在内存中的某个位置:
int arr[10] = {1};
//Some where in memory---> 0x80001f23
[1][1][1][1][1][1][1][1][1][1]
所以如果我说:
*arr
为什么呢?因为它与
arr[0]
是一样的,它给我们提供了数组起始地址处的值。这意味着:
arr; // this is the address of the start of the array
那么这给我们带来了什么?
&arr; //this will give us the address of the array.
//which IS the address of the start of the array
//this is where arrays and pointers really show some difference
所以
arr == &arr;
。数组的“工作”是保存数据,数组不会“指向”任何其他东西,因为它保存着自己的数据。而指针的工作是指向其他东西:
int *z; //the pointer holds the address of someone else's values
z = arr; //the pointer holds the address of the array
z != &z; //the pointer's address is a unique value telling us where the pointer resides
//the pointer's value is the address of the array
编辑:
另一种思考这个问题的方式:
int b; //this is integer type
&b; //this is the address of the int b, right?
int c[]; //this is the array of ints
&c; //this would be the address of the array, right?
所以这很容易理解,那么这个呢:
*c; //that's the first element in the array
那一行代码告诉你什么?如果我取消引用 c ,那么我得到一个int。这意味着只有简单的 c 是一个地址。因为它是数组的开头,所以它是数组的地址,因此:
c == &c;