pointer increment and dereference (lvalue required error)

孤者浪人 提交于 2019-11-28 14:18:20

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

huon

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!