如何将阵列的所有成员初始化为相同的值 [英] How to initialize all members of an array to the same value
问题描述
我在C大阵(不是C ++,如果有差别)。我想所有成员初始化为相同的值。我可以发誓,我曾经认识一个简单的方法来做到这一点。我可以使用 memset的()
在我的情况,而不是有没有办法做到这一点是内置在C语法?
I have a large array in C (not C++ if that makes a difference). I want to initialize all members to the same value. 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屋!