我需要动态分配这个数组 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/