开发者

In C, why is an array reference a += 2; invalid code

开发者 https://www.devze.com 2023-01-18 05:23 出处:网络
From my lecture slides, it states: As illustrated in the code below an array name can be assigned to an appropriate pointer without the need for a preceding & operator.

From my lecture slides, it states:

As illustrated in the code below an array name can be assigned

to an appropriate pointer without the need for a preceding & operator.

int x;  
int a[3] = {0,1,2};  
int *pa = a;  
x = *pa;  
x = *(pa + 1);  
x = *(pa + 2);  
a += 2; /* invalid */  

Why is a += 2; invalid?

Can anyone help clarify?开发者_运维知识库

Also feel free to edit the title if you think of a better one.


a += 2 gets translated to a = a + 2. Adding a number to an array is the same as adding a number to a pointer which is valid and yields a new pointer.

The assignment is the problem - arrays are not lvalues, so you cannot assign anything to them. It is just not allowed. And even if you could there is a type mismatch here - you’re trying to assign a pointer to an array which does not make sense.


a += 2; is invalid because += operator isn't defined for arrays. Furthermore arrays are non modifiable lvalues so you cannot assign to them.


When you pass a to a function where a pointer is expected, the address of a is used. This leads to the wrong statement, an array and a pointer are interchangeable.

But

  • a is an array
  • pa is a pointer

Since pa is a scalar, you can modify it with

pa = pa + 2;

or

pa += 2;

The array a does not define any operation like

a = a + 2;  /* invalid */


when you write a += 2 then it translated to a = a + 2.

So it means you modify base address of array. That is not allow in c because if you modify base address of array then how you access array element.

It will give Lvalue required error at compile time.

0

精彩评论

暂无评论...
验证码 换一张
取 消