首页 > 解决方案 > 如何在C中将数组初始化为全0?

问题描述

陷入最简单的问题。

int *p= (int *)malloc(m*sizeof(int));
p={0}; // this is not correct.

除了使用循环之外,如何将整个数组设置为值 0?

标签: c

解决方案


使用calloc()而不是malloc()在第一个实例中分配已经归零的内存,使用或memset()在分配之后:

 int * p = calloc(m, sizeof(int));

或者

int * p = malloc(m * sizeof(int));
memset(p, 0, m * sizeof(int));

显然,前者更可取。


推荐阅读