请帮助修复此程序。 我尝试使用指针而不是数组打印指针数组但是我收到了这个错误:
pointer_multi_char4.c: In function ‘main’:
pointer_multi_char4.c:7:11: error: expected expression before ‘{’ token
这是代码:
#include <stdio.h>
int main (void){
char **message;
message= { "Four", "score", "and", "seven",
"years", "ago,", "our", "forefathers" };
printf("%s\n",message);
return 0;
}
我该如何修复此代码? 请有人解释一下该代码有什么问题
答案 0 :(得分:5)
#include <stdio.h>
int main (){
char *message[] = { "Four", "score", "and", "seven",
"years", "ago,", "our", "forefathers", 0 };
int loop;
for (loop = 0; message[loop]; ++loop) printf("%s\n",message[loop]);
return 0;
}
这种情况下的大括号(做出假设)是你想要初始化一个数组(因此使用char *message[]
代替char **
。
因为它是一个需要遍历它的数组。我使用空指针来标记数组的结尾
修改强>
然后@Lundu只需要
#include <stdio.h>
int main()
{
const char * mesage="Four scor and seven years .... forefathers";
printf("%s\n", message);
return 0;
}
答案 1 :(得分:1)
#include <stdio.h>
int main (void){
char **message;
message= (char* []){ "Four", "score", "and", "seven",
"years", "ago,", "our", "forefathers" };
int numOfMessage = 8;
while(numOfMessage--){
printf("%s\n", *message++);
}
return 0;
}