如何只用一些值初始化数组的少数元素? [英] How to initialize only few elements of an array with some values?
问题描述
这可能是一个愚蠢的问题,但是否可以将 some 值分配给数组而不是全部?澄清我想要什么:
This might be a stupid question, but is it possible to assign some values to an array instead of all? To clarify what I want:
如果我需要像 {1,0,0,0,2,0,0,0,3,0,0,0}
这样的数组,我可以像这样创建它:
If I need an array like {1,0,0,0,2,0,0,0,3,0,0,0}
I can create it like:
int array[] = {1,0,0,0,2,0,0,0,3,0,0,0};
这个数组的大多数值都是0".是否可以跳过此值并仅分配值 1、2 和 3?我想到了类似的东西:
Most values of this array are '0'. Is it possible to skip this values and only assign the values 1, 2 and 3? I think of something like:
int array[12] = {0: 1, 4: 2, 8: 3};
推荐答案
是否可以跳过这些值而只分配值 1、2 和 3?
Is it possible to skip this values and only assign the values 1, 2 and 3?
在 C 中,是的.使用指定的初始化程序(在 C99 中添加,在 C++ 中不支持).
In C, Yes. Use designated initializer (added in C99 and not supported in C++).
int array[12] = {[0] = 1, [4] = 2, [8] = 3};
上面的初始化器将使用值 1 初始化数组
array
的元素 0
、4
和 8
、2
和 3
.其余元素将使用 0
进行初始化.这将相当于
Above initializer will initialize element 0
, 4
and 8
of array array
with values 1
, 2
and 3
respectively. Rest elements will be initialized with 0
. This will be equivalent to
int array[12] = {1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0};
最好的部分是列出元素的顺序无关紧要.也可以这样写
The best part is that the order in which elements are listed doesn't matter. One can also write like
int array[12] = {[8] = 3, [0] = 1, [4] = 2};
但请注意,[ ]
中的表达式应该是一个整数常量表达式.
But note that the expression inside [ ]
shall be an integer constant expression.
这篇关于如何只用一些值初始化数组的少数元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!