c - 在 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;
解决方案
您需要在单引号之间定义一个字符
#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;
}
推荐阅读
- python - Django表单:如何设置字段的初始值,它当前包含在数据库中的值
- mysql - 通过特定的自定义字段订购 WP 查询,不起作用
- python - 使用 auto_arima(SARIMAX) 和傅里叶项预测具有多个季节性的时间序列
- html - 如何使 div 的大小与其父 div 大小相同
- java - Tomcat 从 ps -ef 对环境变量保密
- cockroachdb - 关闭 cockroachdb 单节点集群中的时间序列数据
- javascript - 为什么在循环一个空数组后在 angular12 中出现“无法编译错误”?
- powerbi - PowerBI:地图可视化未识别巴西“帕拉”州
- razor - 发布后是否可以在 MVC5 网站页脚中显示版本号?
- symfony - 带有 GetSetMethodNormalizer 的 Symfony 序列化程序返回一个空数组而不是日期