【发布时间】:2019-09-29 17:02:13
【问题描述】:
我正在尝试创建动态多维数组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);
我的代码有什么问题?
【问题讨论】:
-
激活编译器中的警告并阅读它们。
标签: c arrays pointers memory-management