不,您的代码没有任何问题。就像你在想的那样……我想得越多,我就越难以解释,所以在我开始讨论之前,请记住以下几点:
- 数组不是指针,不要那样想它们,它们是不同的类型。
- [] 是一个运算符。这是一个移位和顺从运算符,所以当我写作时,
printf("%d",array[3]);
我正在移位和顺从
所以一个数组(让我们考虑一维开始)在内存中的某个地方:
int arr[10] = {1};
//Some where in memory---> 0x80001f23
[1][1][1][1][1][1][1][1][1][1]
所以如果我说:
*arr; //this gives the value 1
为什么?因为它与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;