In C, why the reference to the array is a + = 2; Incorrect code

From my lecture slides it says:

As shown in the code below, the array name can be assigned to the corresponding pointer without the need for the previous and 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 it a += 2;invalid?

Can anyone help clarify?
Also feel free to edit the title if you are thinking of the best.

+3
source share
4 answers

a += 2goes to a = a + 2. Adding a number to an array is the same as adding a number to a pointer, which is valid and gives a new pointer.

- - lvalues, . . - , .

+8

a += 2; , += . , lvalues, .

+7

a , , a. , .

  • a -
  • pa -

pa ,

pa = pa + 2;

pa += 2;

a - ,

a = a + 2;  /* invalid */
+2

+ = 2, a = a + 2.

So this means that you are changing the base address of the array. This is not allowed in c, because if you change the base address of the array, then how do you access the element of the array.

It will give Lvalue the required error at compile time.

0
source

Source: https://habr.com/ru/post/1767146/


All Articles