[英]Stepping through an array of pointers to strings - “lvalue required as increment operand”
我對這個程序很困惑,我將在這里說明。 我寫了兩個簡單的程序來打印字符串列表。 首先,我創建了一個指向字符串的指針數組。 這就是我嘗試這樣做的方式
#include <stdio.h>
int main()
{
int i = 2;
char *a[] = {"Hello", "World"};
while (--i >= 0) {
printf("%s\n", *a++); // error is here.
}
return 0;
}
我需要它打印
Hello
World
但有編譯錯誤,它說,
lvalue required as increment operand.
然后我將程序更改為以下內容
#include <stdio.h>
void printout(char *a[], int n)
{
while (n-- > 0)
printf("%s\n", *a++);
}
int main()
{
int i = 2;
char *a[] = {"Hello", "World"};
printout(a,i);
return 0;
}
然后它按預期工作。
我的問題是,當我將數組名稱傳遞給函數時會發生什么不同? 為什么它不能第一次工作(我懷疑“數組名稱不能修改”是原因但是為什么在第二個程序中,它允許我增加)?
*a++
++
要求其操作數是可修改的左值。
在第一個示例中, a
是一個數組。 在第二個示例中,當作為參數傳遞給函數時,數組衰減為指針(指向其第一個元素),因此代碼將進行編譯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.