首页 > 解决方案 > 在 C 中使用 malloc 后需要将变量分配给数组

问题描述

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

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;

标签: c

解决方案


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

#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 类型的指针。

如果您word_count[0] = a在某个地方定义了char a = 'a'.

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

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

推荐阅读