C语言 将 C 代码中的数组归零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5636070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Zero an array in C code
提问by Batman
Possible Duplicates:
How to initialize an array to something in C without a loop?
How to initialize an array in C
How can I zero a known size of an array without using a for or any other loop ?
如何在不使用 for 或任何其他循环的情况下将已知大小的数组归零?
For example:
例如:
arr[20] = 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;
This is the long way... I need it the short way.
这是漫长的道路......我需要它的捷径。
回答by Prasoon Saurav
int arr[20] = {0};
C99 [$6.7.8/21]
C99 [$6.7.8/21]
If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
如果花括号括起来的列表中的初始值设定项少于聚合的元素或成员,或者用于初始化已知大小数组的字符串文字中的字符少于数组中的元素 ,则聚合的其余部分应隐式初始化与具有静态存储持续时间的对象相同。
回答by Oleh Prypin
回答by Rúben Lício Reis
Note: You can use memset with any character.
注意:您可以将 memset 与任何字符一起使用。
Example:
例子:
int arr[20];
memset(arr, 'A', sizeof(arr));
Also could be partially filled
也可以部分填充
int arr[20];
memset(&arr[5], 0, 10);
But be carefull. It is not limited for the array size, you could easily cause severe damage to your program doing something like this:
但要小心。它不受数组大小的限制,您可以很容易地执行以下操作对您的程序造成严重损坏:
int arr[20];
memset(arr, 0, 200);
It is going to work (under windows) and zero memory after your array. It might cause damage to other variables values.
它将在您的阵列之后工作(在 Windows 下)和零内存。它可能会损坏其他变量值。
回答by drysdam
man bzero
男人 bzero
NAME
bzero - write zero-valued bytes
SYNOPSIS
#include <strings.h>
void bzero(void *s, size_t n);
DESCRIPTION
The bzero() function sets the first n bytes of the byte area starting
at s to zero (bytes containing 'int something[20];
memset(something, 0, 20 * sizeof(int));
').
回答by iRaivis
Using memset:
使用memset:
回答by Chris
int arr[20] = {0}would be easiest if it only needs to be done once.
int arr[20] = {0}如果只需要完成一次,那将是最简单的。

