1) 指针不是数组。数组不是指针。不要那样想它们,因为它们是不同的。
我怎样才能证明这一点?想想它们在记忆中是什么样子的:
Our array arr
is 10 characters long. It contains "Hello", but wait, that's not all! Because we have a statically declared array longer than our message, we get a bunch of NULL characters ('\0'
) thrown in for free! Also, note how the name arr
is conceptually attached to the contiguous characters, (it's not pointing to anything).
![enter image description here](https://i.stack.imgur.com/oiEdK.jpg)
Next consider how our pointer would look in memory:
Note here we're pointing to a character array some place in read only memory.
所以虽然两者arr
and ptr
以相同的方式初始化,每个的内容/位置实际上是不同的。
这是关键点:
ptr是一个变量,我们可以将它指向任何东西,arr是一个常量,它将始终引用这 10 个字符的块。
2) The []
是一个可以在地址上使用的“添加和引用”运算符。意思是arr[0]
就等于说*(arr+0)
。所以是的,这样做:
printf("%c %c", *(arr+1), *(ptr+1));
会给你一个“e e”的输出。不是因为数组是指针,而是因为数组的名称arr
和一个指针ptr
两者都恰好给了你一个地址。
#2 的要点:解引用运算符*
以及添加和取消引用运算符[]
不分别特定于指针和数组。这些运算符仅处理地址。
3)我没有一个非常简单的答案......所以让我们暂时忘记我们的字符数组,看看这个例子来解释:
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
,然后我得到一个整数。这意味着简单c
是一个地址。由于它是数组的开头,因此它是数组的地址,也是数组中第一个元素的地址,因此从值的角度来看:
c == &c;
4)让我暂时偏离主题……最后一个问题是地址算术混乱的一部分。我曾经看到一个关于 SO 的问题,暗示地址只是整数值......您需要了解在 C 中地址具有类型知识。也就是说:
iarr+1; //We added 1 to the address, so we moved 4 bytes
arr+1; //we added 1 to the address, so we moved 1 byte
基本上是sizeof(int)
是 4 并且sizeof(char)
是 1。所以“向数组添加 1”并不像看起来那么简单。
那么现在回到问题,为什么arr+1
不同于&arr+1
?第一个是添加1 * sizeof(char)
=1到地址,第二个是加1 * sizeof(arr)
=10 到地址。
这就是为什么即使它们都“只加 1”,它们也会给出不同的结果。