C语言 如何在C中将数组初始化为0?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2589749/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:05:20  来源:igfitidea点击:

How to initialize array to 0 in C?

carraysinitialization

提问by Claudiu

I need a big null array in C as a global. Is there any way to do this besides typing out

我需要一个大的 C 中的空数组作为全局。除了打字,还有什么办法可以做到这一点

char ZEROARRAY[1024] = {0, 0, 0, /* ... 1021 more times... */ };

?

?

回答by John Kugelman

Global variables and static variables are automatically initialized to zero. If you have simply

全局变量和静态变量自动初始化为零。如果你有简单的

char ZEROARRAY[1024];

at global scope it will be all zeros at runtime. But actually there isa shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type.You could write:

在全局范围内,它将在运行时全为零。但实际上一个速记语法,如果你有一个本地阵列。如果数组已部分初始化,则未初始化的元素会收到相应类型的值 0。你可以写:

char ZEROARRAY[1024] = {0};

The compiler would fill the unwritten entries with zeros. Alternatively you could use memsetto initialize the array at program startup:

编译器将用零填充未写入的条目。或者,您可以使用memset在程序启动时初始化数组:

memset(ZEROARRAY, 0, 1024);

That would be useful if you had changed it and wanted to reset it back to all zeros.

如果您更改了它并希望将其重置为全零,这将非常有用。

回答by Deqing

If you'd like to initialize the array to values other than 0, with gccyou can do:

如果您想将数组初始化为 0 以外的值,gcc您可以执行以下操作:

int array[1024] = { [ 0 ... 1023 ] = -1 };

This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99to compile your code.

这是 C99指定初始值设定项的 GNU 扩展。在较旧的 GCC 中,您可能需要使用-std=gnu99来编译您的代码。