c - C中使用malloc后需要将变量分配给数组

标签 c

我需要动态分配这个数组 word_count ,然后从函数中返回它。但是,在 malloc 后,我似乎无法将变量分配给 word_count 。它显示错误“需要一个表达式”我是 C 编程新手。我做错了什么。将这些变量分配给该数组的正确方法是什么?短暂性脑缺血发作

int *word_count = malloc(sizeof(char) * 26);
    if(word_count == NULL)
    {
        printf("Not enough memory. Program terminating...\n");
        exit(1);
    }
    /* Allocating variables to to word_count */
    word_count = {a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z};


    return word_count;

最佳答案

您需要在单引号之间定义一个字符

#include <stdio.h>
int main()
{
    char *word_count = malloc(sizeof(char) * 26);
    if(word_count == NULL)
    {
        printf("Not enough memory. Program terminating...\n");
        exit(1);
    }
    /* Allocating variables to to word_count */
    word_count[0] = 'a';
    word_count[1] = 'b';
    word_count[2] = 'c';
    /*...*/
    return word_count;
}

此外,您还有一个分配字符的整数指针。您可以将整数分配给 word_count,或者将 word_count 声明为指向 char 类型的指针。

如果您在某处定义了 char a = 'a',您也可以像 word_count[0] = a 那样分配它。

如果你想自动化它,你也可以在 for 循环中完成

for (int i=0; i<26; i++)
{
    word_count[i] = 'a' + i;
}

关于c - C中使用malloc后需要将变量分配给数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59892010/

相关文章:

c - 在可加载的 linux 内核模块上设置 cpu 亲和性

c - 新程序员,我需要哈佛 CS50 提供的有关greedy.c的帮助

c - 如何将整数数组内容复制到字符指针?

c - 我需要帮助如何从较大的字符串中获取较小的字符串?在C中

c - 如何从命令行正确传递文件路径?

c - 字符串比较函数循环中的“while”循环超出必要

c - 路径问题的算法或方法,n <= 12 的 n 点的最短路径

c - 如何通过进程的回溯确定传递函数参数的值?

c - 这个 C 模式程序有什么问题

c - 纯 C 中的 Knuth-Morris-Pratt 实现