[英]pointer increment and dereference (lvalue required error)
我試圖了解指針遞增和解引用是如何結合在一起的,我這樣做是為了進行嘗試:
#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;
}
我希望這段代碼可以執行以下操作之一:
但是編譯器甚至不會編譯它,並給出以下錯誤: lvalue required as increment operand
我在這里做錯了嗎?
您需要在第二個printf中的指針取消引用周圍加上括號,例如: printf("%s\\n",(*words)++);
另外,如果您嘗試在列表中獲取數字2,則需要使用前綴增量而不是后綴。
您不能遞增數組,但可以遞增指針。 如果將聲明的數組轉換為指針,則可以使用它:
#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;
}
words
是數組的名稱,因此++
毫無意義。 但是,您可以使用指向數組元素的指針:
for (char ** p = words; p != words + 2; ++p)
{
printf("Address: %p, value: '%s'\n", (void*)(p), *p);
}
當然,您可以使用更通用的sizeof(words)/sizeof(*words)
代替2
。
問題在於此行:
printf("%s\n",*words++);
它讀為*(words++)
,即增加一個內存塊。 那沒有意義,有點像嘗試做:
int a = 1;
(&a)++; // move a so that it points to the next address
在C中是非法的
問題是由C中的數組和指針之間的區別引起的:(基本上)數組是內存塊(在編譯時分配),而指針是內存塊的指針(不一定在編譯時分配) 。 這是使用C時的常見問題,因此在SO上還有其他問題(例如C:char指針和array之間的差異 )。
(在其他答案中描述了此修復程序,但是基本上您想使用指向字符串的指針而不是字符串數組。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.