简体   繁体   中英

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.

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. Both work if ar is the name of an array, and both work if ar is a pointer variable. However, using an expression such as ar++ only works if ar is a pointer variable.

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. But why expression such as ar++ only works if ar is a pointer variable? I'm really stuck on the logic behind it.

Suppose arr is an array and arr++ works on it. 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. 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[] .

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++ increments the location of the pointer which points to the array. In general ar++ moves the pointer to the next element in the array. after declaring the array the pointer points the first element or ar[0] initially. ar++ makes the pointer move to the next element or ar[1] and so on.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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