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?
words
is the name of the array, so++
makes no sense on it. You can take a pointer to the array elements, though:Instead of
2
you can of course use the more genericsizeof(words)/sizeof(*words)
.The problem is with this line:
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: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.)
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.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: