why can not we increment an array in similiar way

2019-06-14 15:39发布

This question already has an answer here:

#include <stdio.h>

int main(){
    int arr[] = {1, 2, 3, 4};
    int *p;
    p = arr;
    printf("%d\n", *p);
    printf("%d\n", *arr);
    p++;
    printf("%d\n", *p);
}

This code outputs:

1
1
2

but when we add 2 lines as below:

 #include <stdio.h>

    int main(){
        int arr[] = {1, 2, 3, 4};
        int *p;
        p = arr;
        printf("%d\n", *p);
        printf("%d\n", *arr);
        p++;
        printf("%d\n", *p);
        arr++;
        printf("%d\n", *arr);
    }

This code outputs:

C:\Users\Hasnat\Desktop\test.c||In function 'main':|
C:\Users\Hasnat\Desktop\test.c|11|error: lvalue required as increment operand
=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===

Why can not we increment an array in same way we increment pointer containing address of that array to get next element??

2条回答
老娘就宠你
2楼-- · 2019-06-14 16:11

Because C doesn't allow assigning to array. Arrays in expressions are automatically converted to a pointer pointing at the first element of the array unless they are used for the operand of sizeof operating or unary & (address) operator. (N1256 6.3.2.1)

As the error message shows, the operand arr is converted to a pointer pointing the first element of the array and the pointer isn't a lvalue, so it cannot be modified via increment operator.

查看更多
Ridiculous、
3楼-- · 2019-06-14 16:26

To quote C11, chapter 6.5.2.4, Postfix increment and decrement operators

The operand of the postfix increment or decrement operator shall have atomic, qualified, or unqualified real or pointer type, and shall be a modifiable lvalue.

and the definition of modifiable lvalue is given in chapter 6.3.2.1 of the same standard, Lvalues, arrays, and function designators

An lvalue is an expression (with an object type other than void) that potentially designates an object; [...] A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a constqualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a constqualified type.

So, you cannot use ++ on an array. Simple.

查看更多
登录 后发表回答