pointer increment and dereference (lvalue required

2019-01-20 14:23发布

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:

  1. First dereference then increase the pointer (printing word1)
  2. First dereference then increase the value (printing ord1)
  3. 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?

4条回答
疯言疯语
2楼-- · 2019-01-20 14:53

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).

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-20 14:53

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.)

查看更多
成全新的幸福
4楼-- · 2019-01-20 14:57

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.

查看更多
手持菜刀,她持情操
5楼-- · 2019-01-20 15:00

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;
}
查看更多
登录 后发表回答