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

时间:2021-04-03 22:34:36

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

我需要一个大的空数组作为全局变量。除了打字之外,还有什么别的办法吗

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

?

吗?

2 个解决方案

#1


202  

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 is a 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。但是如果你有一个本地数组,实际上有一个简写语法。如果数组被部分初始化,则未初始化的元素将接收适当类型的值0。你可以写:

char ZEROARRAY[1024] = {0};

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

编译器会用0填充未写的条目。也可以使用memset在程序启动时初始化数组:

memset(ZEROARRAY, 0, 1024);

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

如果您更改了它并想将它重置为所有的0,那么这将非常有用。

#2


19  

If you'd like to initialize the array to values other than 0, with gcc you 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=gnu99 to compile your code.

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

#1


202  

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 is a 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。但是如果你有一个本地数组,实际上有一个简写语法。如果数组被部分初始化,则未初始化的元素将接收适当类型的值0。你可以写:

char ZEROARRAY[1024] = {0};

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

编译器会用0填充未写的条目。也可以使用memset在程序启动时初始化数组:

memset(ZEROARRAY, 0, 1024);

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

如果您更改了它并想将它重置为所有的0,那么这将非常有用。

#2


19  

If you'd like to initialize the array to values other than 0, with gcc you 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=gnu99 to compile your code.

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