如何仅初始化具有某些值的数组中的几个元素? [英] How to initialize only few elements of an array with some values?

查看:159
本文介绍了如何仅初始化具有某些值的数组中的几个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但是是否可以将一些值分配给数组而不是全部?要澄清我想要什么:

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};  

以上初始化程序将分别使用值123初始化数组array的元素048.其余元素将使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆