我已經定義串的恆定陣列打印
static const char *Props[] = {"Cp", "Cv", "Mu", "H"};
只在C使用指針字符串數組而執行以下我得到錯誤:
while(*Props) printf("%s\n", *Props++);
錯誤信息是:
C/test.c:38:45: error: lvalue required as increment operand
任何人都可以請解釋爲什麼我得到這個錯誤?
我已經定義串的恆定陣列打印
static const char *Props[] = {"Cp", "Cv", "Mu", "H"};
只在C使用指針字符串數組而執行以下我得到錯誤:
while(*Props) printf("%s\n", *Props++);
錯誤信息是:
C/test.c:38:45: error: lvalue required as increment operand
任何人都可以請解釋爲什麼我得到這個錯誤?
數組指示符是不可修改的左值。你不能改變它們。你需要的是以下內容
static const char *Props[] = {"Cp", "Cv", "Mu", "H"};
for (size_t i = 0; i < sizeof(Props)/sizeof(*Props); i++)
{
puts(Props[i]);
}
另一種方法是給數組添加一個標記值。例如
static const char *Props[] = {"Cp", "Cv", "Mu", "H", NULL };
for (const char **s = Props; *s; s++)
{
puts(*s);
}
只爲滿足這個奇怪的問題要求的目的:
#include <stdio.h>
static void
print_props(void)
{
static const char *Props[] = {"Cp", "Cv", "Mu", "H"};
const char **b = Props;
const char **e = Props + sizeof(Props)/sizeof(Props[0]);
do {
puts(*(b++));
} while (b != e);
return;
}
int
main(void)
{
print_props();
return 0;
}
然而,僅僅使用一個for
循環。
它不起作用的工作原因與int array [] = {1,2}; array++;
不起作用。
您不能在陣列類型上應用++
。您需要一個指向數組第一項的指針。因此,一個解決辦法是要做到這一點:
const char** ptr = &Props[0];
while(*ptr) printf("%s\n", *ptr++);
但是,這是非常可怕的代碼還包含另一個缺陷,即缺乏陣列中的結束條件。爲了使這個解決方案能夠工作,陣列應該被聲明爲{"Cp", "Cv", "Mu", "H", NULL};
。
不要做這樣的奇怪的事情,只是因爲你可以。正如另一個答案中所演示的那樣,只需使用for循環和一個整數迭代器即可。
數組本身是一個常量。它不能改變。 'static const char * Props [] = {「Cp」,「Cv」,「Mu」,「H」,NULL}; \t const char ** p = Props; (* p)printf(「%s \ n」,* p ++);' – BLUEPIXY
但是當我編寫 時,程序執行時(* Props)printf(「%s \ n」,*(Props + 1) ); 爲什麼? – skrath
「道具+ 1」不會改變「道具」。 '道具+ 1'並不意味着'道具=道具+ 1' – BLUEPIXY