c - 为 char **foobar 或 char *foobar[] 分配 malloc,如何进行?

标签 c char malloc

我想知道当你有一个单词数组(char **words 甚至 char *words[] 时如何分配内存。

最佳答案

你可以试试这个:

    char **words;
    words = malloc(sizeof(char)*MAX_WORD_SIZE*MAX_NUM_WORDS);

    if (words == 0)
    {
        printf("ERROR: Out of memory\n");
        return 1;
    }
            .... <use words>
    free(words);

其中 MAX_WORD_SIZE 是字符串可能具有的最大长度(减去“\0”终止字符); MAX_NUM_WORDS 是您要管理的最大字数。

上面的代码将分配内存来保存您想要管理的所有单词。

您还可以使用calloc,它的一大优点是将内存设置为“0”,这在处理字符串时非常有用:

    words = (char**)calloc(MAX_NUM_WORDS, sizeof(char)*MAX_WORD_SIZE);

关于c - 为 char **foobar 或 char *foobar[] 分配 malloc,如何进行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7000596/

相关文章:

c++ - 尝试计算二维数组中的特定字符,但计算整个数组

c - 动态内存分配(malloc): why does the whole string get printed even though I did not allocate required memory?

c - c中没有堆吗?

c - 理解 C 语言中的 StrBuff

java - 音频时间尺度音调修改 - 开源示例?

c - 如何用c语言为实时linux操作系统创建一个中断服务函数?

c - 如何在启动时在 CLion 中配置 CMakeLists.txt?

c - 为什么程序的输出会在计算机之间发生变化

ios 将带有特殊字符的 NSString 转换为 const char

c++ - 错误: cannot convert ‘std::string {aka std::basic_string<char>}’ to ‘char*’ in initialization