Inconsistent lvalue required error when incrementing array variable

后端 未结 3 1261
广开言路
广开言路 2021-01-19 19:54

I am getting \"lvalue required as increment operand\" while doing *++a. Where I am going wrong? I thought it will be equivalent to *(a+1). This beh

相关标签:
3条回答
  • 2021-01-19 20:26

    ++a and a + 1 are not equivalent. ++a is the same as a = a + 1, i.e it attempts to modify a and requires a to be a modifiable lvalue. Arrays are not modifiable lvalues, which is why you cannot do ++a with an array.

    argv declaration in main parameter list is not an array, which is why you can do ++argv. When you use a[] declaration in function parameter list, this is just syntactic sugar for pointer declaration. I.e.

    int main(int argc, char *argv[])
    

    is equivalent to

    int main(int argc, char **argv)
    

    But when you declare an array as a local variable (as in your question), it is indeed a true array, not a pointer. It cannot be "incremented".

    0 讨论(0)
  • 2021-01-19 20:40

    a is a constant(array name) you can't change its value by doing ++a, that is equal to a = a + 1.
    You might wanted to do *a = *a + 1 (increment 0 indexed value), for this try *a++ instead. notice I have changed ++ from prefix to postfix.

    Note: char* argv[] is defined as function parameter and argv is pointer variable of char** type ( char*[]).
    Whereas in your code int* a[] is not a function parameter. Here a is an array of int type (int*)(array names are constant). Remember declaration in function parameter and normal declarations are different.

    Further, by using ++ with argv and a you just found one difference, one more interesting difference you can observe if you use sizeof operator to print there size. for example check this working code Codepade

    int main(int argc, char* argv[]){
        int* a[2];
        printf(" a: %u, argv: %u", sizeof(a), sizeof(argv));
        return 1;
    }
    

    Output is:

    a: 8, argv: 4
    

    Address size in system is four bytes. output 8 is size of array a consists of two elements of type int addresses (because a is array), whereas 4 is size of argv (because argv is pointer).

    0 讨论(0)
  • 2021-01-19 20:40

    Arrays are not pointers. a is an array; you cannot increment an array.

    0 讨论(0)
提交回复
热议问题