【问题标题】:Runtime error when creating dynamic multidimensional array of pointers (char**) [closed]创建动态多维指针数组(char**)时出现运行时错误[关闭]
【发布时间】: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


【解决方案1】:

printf("%s\n", *str[i]); 应该是printf("%s\n", str[i]);

*str[i]char,但 %s 需要 char *。你的编译器应该已经警告你了。如果没有,请在编译器中启用警告,并注意它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 2020-06-01
    • 2020-04-06
    相关资源
    最近更新 更多