I have this code:
char *name[] = { "a1", "b2", "c3", "d4" };
printf("%s\n", *name); //the critical line
Related to critical line:
In this form, the output is simple: a1.
If I replace the critical line with:
printf("%s\n", ++*name);
then the output is 1. I think until now everything is good.
Taking in account that name is a pointer to the first string of characters, respectively "a1", I replace the critical line with:
printf("%s\n", ++name);
in the hope that I’ll get "b2" result as output. But I get this error:
../src/test.c:32: error: lvalue required as increment operand.
Question: I can’t understand why ++*name is legal – name is a pointer to first string of characters – and ++name isn’t. In my opinion, the ++name should move the name to the next string of characters. Can anybody explain me where is the lack in my understing?
When you write
++name, the arraynameis converted to a pointer to the first element of the array. The result of this conversion is not an lvalue, and it can’t be modified with++or otherwise. You could instead writename+1, which would print the right thing. Whennameis an array, there is no way to modify it to refer to anything other than that array[*].Consider also:
Roughly speaking, an “lvalue” is an expression that refers to an object, whereas a “not an lvalue” is an expression that has a value. The difference between an object and a value, is that an object is a place for storing values (well, one value at a time). Values can never be modified, objects sometimes can.
Whenever you have a subexpression which is an lvalue but whose current value is needed, the object is read/loaded/whatever you want to call it. In C++ this is called an “lvalue to rvalue conversion”, I can’t remember whether it’s called anything in C other than “evaluating the subexpression”.
[*] you can shadow it with another variable
namein an inner scope, that refers to something else. But that’s still not modifying the outername, just temporarily hiding it.