c - 如何在C中将数组初始化为全0?
问题描述
陷入最简单的问题。
int *p= (int *)malloc(m*sizeof(int));
p={0}; // this is not correct.
除了使用循环之外,如何将整个数组设置为值 0?
解决方案
使用calloc()
而不是malloc()
在第一个实例中分配已经归零的内存,使用或memset()
在分配之后:
int * p = calloc(m, sizeof(int));
或者
int * p = malloc(m * sizeof(int));
memset(p, 0, m * sizeof(int));
显然,前者更可取。
推荐阅读
- php - 如何通过 id 从 laravel 特定表中传递数据
- java - Intellij idea 对位于其他驱动器上的任何文件说只读文件系统
- angular - “事件”类型的参数不可分配给“字符串”类型的参数
- python - 如何使用正则表达式在一两个匹配组之后捕获句子的其余部分?
- postgresql - pgr_dijkstra 返回空结果
- postgresql - Postgres 函数将一对 64 位数字转换为表示 128 位数字的字符串
- swift - 结果与组合无法获得结果
- javascript - 为什么设置 autocompleteSearchBox componentRestrictions 国家对象谷歌地图不会改变它的位置?
- jquery - 如何反转砌体网格的文本叠加和图像?
- php - 使用 laravel API 上传多张图片:具有多态关系