简体   繁体   English

当在C中使用诸如anArray ++之类的表达式时,数组和指针之间的差异

[英]Difference between arrays and pointer when expression such as anArray++ is used in C

I'm currently studying C using the book "C Primer Plus 6th edition. 我目前正在使用“C Primer Plus第6版”这本书学习C语言。

In the chapter on arrays and pointers, the author states 在关于数组和指针的章节中,作者说

As far as C goes, the two expressions ar[i] and *(ar+i) are equivalent in meaning. 就C而言,两个表达式ar [i]和*(ar + i)在含义上是等价的。 Both work if ar is the name of an array, and both work if ar is a pointer variable. 如果ar是数组的名称,则两者都有效,如果ar是指针变量,则两者都有效。 However, using an expression such as ar++ only works if ar is a pointer variable. 但是,使用诸如ar ++之类的表达式只有在ar是指针变量时才有效。

I thought in c, ar[0] and *(ar + 0) is equivalent and they both equal to the value contained in index 0 of the array. 我认为在c中, ar[0]*(ar + 0)是等价的,它们都等于数组索引0中包含的值。 But why expression such as ar++ only works if ar is a pointer variable? 但是,如果ar是一个指针变量,为什么像ar++这样的表达式才有效? I'm really stuck on the logic behind it. 我真的坚持它背后的逻辑。

Suppose arr is an array and arr++ works on it. 假设arr是一个数组, arr++可以使用它。 So, what supposed to do? 那么,应该做什么? If it is incremented, now, where is the pointer into the first element of the array? 如果它递增,那么,指针到数组的第一个元素的位置在哪里? Therefore, it does not make sense the value of an array, which is pointed to the first element of the array, could be incremented and it is not logical anymore. 因此,指向数组的第一个元素的数组的值可以递增并且它不再是逻辑的,这是没有意义的。

On the other side, if arr is a pointer, it could be moved and set to other places. 另一方面,如果arr是一个指针,它可以被移动并设置到其他地方。 Therefore, it makes sense you can change the value of the pointer. 因此,您可以更改指针的值。

In sum, although this fact is true which the name of the array pointed to the first element of an allocated array, it does not make sense to be set or changed over time like a pointer. 总而言之,虽然这个事实是正确的,其中数组的名称指向已分配数组的第一个元素,但是像指针一样随时间设置或更改是没有意义的。

ar++

evaluates to 评估为

ar=ar+1 this won't work for the array ar[] simply because an array once declared won't allow you to change its starting index permanently and that is indeed the primary difference between *arr and arr[] . ar=ar+1这对数组ar[]不起作用,因为一旦声明的数组将不允许你永久地改变它的起始索引,这确实是*arrarr[]之间的主要区别。

The fact that, for an array ar[] , ar[1] and *(ar+1) works is because pointer type arithmetic or pointer notation can be used for an array and vice versa and both should produce the same code. 事实上,对于数组ar[]ar[1]*(ar+1)工作原理是因为指针类型算术或指针符号可用于数组,反之亦然,两者都应产生相同的代码。

ar++ increments the location of the pointer which points to the array. ar ++增加指向数组的指针的位置。 In general ar++ moves the pointer to the next element in the array. 通常,ar ++将指针移动到数组中的下一个元素。 after declaring the array the pointer points the first element or ar[0] initially. 在声明数组之后,指针最初指向第一个元素或ar [0]。 ar++ makes the pointer move to the next element or ar[1] and so on. ar ++使指针移动到下一个元素或ar [1],依此类推。

ar++相当于ar = ar + 1.所以基本上它是一个赋值,所以通过增量我们改变了一个不允许的数组的基址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM