I am trying to understand how pointer incrementing and dereferencing go together, and I did this to try it out:
#include <stdio.h>
int main(int argc, char *argv[])
{
char *words[] = {"word1","word2"};
printf("%p\n",words);
printf("%s\n",*words++);
printf("%p\n",words);
return 0;
}
I expected this code to do one of these:
- First dereference then increase the pointer (printing word1)
- First dereference then increase the value (printing ord1)
- Dereference pointer + 1 (printing word2)
But compiler won't even compile this, and gives this error: lvalue required as increment operand
am I doing something wrong here?
You cannot increment an array, but you can increment a pointer. If you convert the array you declare to a pointer, you will get it to work:
#include <stdio.h>
int main(int argc, char *argv[])
{
const char *ww[] = {"word1","word2"};
const char **words = ww;
printf("%p\n",words);
printf("%s\n",*words++);
printf("%p\n",words);
return 0;
}
You need to put braces around the pointer dereference in the second printf, e.g.:printf("%s\n",(*words)++);
Also, if you're attempting to get number 2 in your list there, you need to use the prefix increment rather than postfix.
words
is the name of the array, so ++
makes no sense on it. You can take a pointer to the array elements, though:
for (char ** p = words; p != words + 2; ++p)
{
printf("Address: %p, value: '%s'\n", (void*)(p), *p);
}
Instead of 2
you can of course use the more generic sizeof(words)/sizeof(*words)
.
The problem is with this line:
printf("%s\n",*words++);
It is read as *(words++)
, i.e. increment a block of memory. That doesn't make sense, it is a bit like trying to do:
int a = 1;
(&a)++; // move a so that it points to the next address
which is illegal in C.
The problem is caused by the distinction between arrays and pointers in C: (basically) an array is a block of memory (allocated at compile time), while a pointer is a pointer to a block of memory (not necessarily allocated at compile time). It is a common trip-up when using C, and there are other question on SO about it (e.g. C: differences between char pointer and array).
(The fix is described in other answers, but basically you want to use a pointer to strings rather than an array of strings.)
来源:https://stackoverflow.com/questions/10150428/pointer-increment-and-dereference-lvalue-required-error