如何将数组的所有成员初始化为相同的值? [英] 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屋!