我正在尝试创建动态多维数组char **变量来存储三个字符串,但是在运行时发生未知错误。
// Allocate memory for three strings
char **str = (char**) malloc(sizeof(char*)*3);
for(int i=0;i<3;i++)
str[i] = (char*) malloc(20);
// Assign value to each string item
strcpy(str[0], "LionKing");
strcpy(str[1], "Godzilla");
strcpy(str[2], "Batman");
// Print the strings
for(int i=0;i<3;i++)
printf("%s\n", *str[i]);
// Free the memory of the three strings
for(int i=0;i<3;i++)
free(str[i]);
// Free the memory of the main pointer
free(str);
我的代码有什么问题?
[printf("%s\n", *str[i]);
应为printf("%s\n", str[i]);
。
*str[i]
是char
,但%s
需要char *
。您的编译器应该已经对此发出警告。如果没有,请在编译器中启用警告,并注意它们。
您正在打印指针而不是字符串。
我在编译期间发出警告:warning: format ‘%s’ expects argument of type ‘char*’, but argument 2 has type ‘int’
将其更改为:printf("%s\n", str[i]);