Lvalue inconsistency requires error when adding array variable

I get "lvalue required as an increment operand" when doing *++a . Where am I mistaken? I thought this would be equivalent to *(a+1) . This behavior is strange since *++argv working fine. Please, help.

 #include <stdio.h> int main(int argc, char *argv[]) { printf("Arg is: = %s\n", *++argv); int a1[] = {1,2,3,4,5,6}; int a2[] = {7,8,9,10,11,12}; int *a[2]; a[0] = a1; a[1] = a2; printf("ptr = %d\n", *++a); return 0; } 
+4
source share
3 answers

a is a constant (array name), you cannot change its value by doing ++a equal to a = a + 1 .
You might want to do *a = *a + 1 (increment 0 with an indexed value), try *a++ instead. Notice that I changed ++ from prefix to postfix.

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

Next, using ++ with argv and a , you found only one difference, another interesting difference that you can see if you use the sizeof operator to print the size there. for example check this working codepade code

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

Output:

 a: 8, argv: 4 

The address size in the system is four bytes. output 8 - the size of the array a consists of two elements of type int addresses (because a is an array), while 4 is the size of argv (because argv is a pointer).

+5
source

++a and a + 1 are not equivalent. ++a coincides with a = a + 1 , i.e. it tries to change a and requires that a be a mutable value of l. Arrays are not modified by lvalues, so you cannot do ++a with an array.

argv declaration in the main parameter list is not an array, so you can do ++argv . When you use the declaration of a[] in the list of function parameters, it is just syntactic sugar for declaring a pointer. I.e

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

equivalently

 int main(int argc, char **argv) 

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

+4
source

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

+3
source

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


All Articles