有人可以解释一下我在这里做错了什么吗? 我正在尝试像这样分配“多维”动态数组。
谢谢
enum { MAX_WORDS = 100, MAX_LENGHT = 20 };
char **words;
// it fails here "void * cannot be assigned... type of char**"
words = malloc(MAX_WORDS * sizeof(char*));
for (int i = 0; i < MAX_WORDS; i++) {
words[i] = malloc(MAX_LENGHT * sizeof(char));
}
最佳答案
words = malloc(MAX_WORDS * sizeof(char*));
应该阅读
words = (char**)malloc(MAX_WORDS * sizeof(char*));
你的编译器很生气,因为你试图分配一个指向 char 指针的 void,因此你需要将其类型转换为 char** 才能正常工作。
编辑:显然这是因为我使用的是 C++ 编译器。在 C 中,您不应该转换 malloc() 的结果。如果您使用 C++,您应该切换到 new 并删除(如果可能)。
关于c - 无法 malloc char**,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35411490/