我不明白为什么这段代码是错误的,它说需要左值作为递增操作数。但是行星不是一组指向字符串的指针吗?所以 planets++ 不应该带我到下一个字符串吗? example- planets 是指向字符串“mercury”的指针。当我做行星++时,它不应该带我去“金星”
#include <stdio.h>
int main()
{
char* planets[] = {"Mercury", "Venus", "Earth","Mars","Jupiter",
" Saturn", "Uranus", "Neptune", "Pluto"};
int count = 0;
for(planets; planets <= planets + 8;planets++){
if(**planets == 'M'){
count++;
}// if
}// for
printf("\n%d",count);
}
最佳答案
您对行星
的描述是准确的;它被定义为一个指针数组。强调其中的 array 部分,因为这意味着使用其 id 不符合左值操作(如后递增)的资格。
如果您想使用指针表示法遍历该指针数组,可以使用键控到数组类型的适当的指针到指针来完成。如果数组是 const char*
的数组,则指向 const char *
的指针(即 const char **
)是合适的。
像这样:
#include <stdio.h>
int main()
{
const char *planets[] = {
"Mercury", "Venus", "Earth", "Mars", "Jupiter",
"Saturn", "Uranus", "Neptune", "Pluto"
};
int count = 0;
for(const char **p = planets; p != planets + 9; ++p)
{
if(**p == 'M'){
count++;
}// if
}// for
printf("%d\n",count);
}
输出
2
关于c - 这段代码有什么问题?它给出错误 - 需要左值作为增量操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58576938/