如何将数组的所有成员初始化为相同的值? [英] How to initialize all members of an array to the same value?
问题描述
我在 C 中有一个大型阵列(如果有所不同,则不是 C ++ ).我想初始化所有具有相同值的成员.
I have a large array in C (not C++ if that makes a difference). I want to initialize all members of the same value.
我可以发誓,我曾经知道一种简单的方法来做到这一点.我可以使用memset()
,但是没有办法直接在C语法中内置吗?
I could swear I once knew a simple way to do this. I could use memset()
in my case, but isn't there a way to do this that is built right into the C syntax?
推荐答案
除非该值为0(在这种情况下,您可以省略初始化器的某些部分 并且相应的元素将被初始化为0),没有简单的方法.
Unless that value is 0 (in which case you can omit some part of the initializer and the corresponding elements will be initialized to 0), there's no easy way.
不过,请不要忽略明显的解决方案:
Don't overlook the obvious solution, though:
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
缺少值的元素将初始化为0:
Elements with missing values will be initialized to 0:
int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0...
因此,这会将所有元素初始化为0:
So this will initialize all elements to 0:
int myArray[10] = { 0 }; // all elements 0
在C ++中,空的初始化列表还将所有元素初始化为0. 对于C:不允许
In C++, an empty initialization list will also initialize every element to 0. This is not allowed with C:
int myArray[10] = {}; // all elements 0 in C++
请记住,如果没有,则具有静态存储持续时间的对象将初始化为0 指定了初始化程序:
Remember that objects with static storage duration will initialize to 0 if no initializer is specified:
static int myArray[10]; // all elements 0
"0"并不一定意味着全零",因此使用上面的是 比memset()更好,更可移植. (浮点值将为 初始化为+0,指向空值的指针等)
And that "0" doesn't necessarily mean "all-bits-zero", so using the above is better and more portable than memset(). (Floating point values will be initialized to +0, pointers to null value, etc.)
这篇关于如何将数组的所有成员初始化为相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!