我有一个名为arr_[6]
的数组,想要包含六个字符串......但是当我声明这个数组编译器时会抛出错误。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
char arr_1[]= {"My_name","your Name", "His Name"};
char *arr_p;
arr_p = malloc(sizeof(char)*6);
arr_p = arr_1;
printf("%s\n",*arr_p);
system("PAUSE");
return 0;
}
显示的错误如下:
> main.c: In function `main': main.c:9: error: excess elements in char
> array initializer main.c:9: error: (near initialization for `arr_1')
> main.c:9: error: excess elements in char array initializer main.c:9:
> error: (near initialization for `arr_1')
>
> make.exe: *** [main.o] Error 1
请帮助我!
答案 0 :(得分:1)
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
const char *arr_1[]= {"My_name","your Name", "His Name"}; // has to be an array of <char *>
//arr_p is not necessary
printf("%s\n",*arr_1); // will print the first string, "My_name"
printf("%s\n",arr_1[1]); // will print the second string, "your Name"
printf("%s\n",arr_1[2]); // will print the third string, "His Name"
system("PAUSE");
return 0;
}
答案 1 :(得分:0)
我相信你所寻找的是:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
char* arr_1[]= {"My_name","your Name", "His Name", NULL};
char** arr_p;
arr_p = arr_1;
i = 0;
while (arr_p[i] != NULL)
{
printf("%s\n",(arr_p[i]));
++i;
}
system("PAUSE");
return 0;
}
以下是我所做的更改列表:
char* arr_1[]
声明一个字符串数组,因为每个字符串都是一个字符数组。char**
while
循环迭代所有字符串。