使用C中的单个值初始化数组(GCC) [英] Initialize an array with a single value in C (GCC)

查看:126
本文介绍了使用C中的单个值初始化数组(GCC)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在头文件中声明了一个数组,如下所示:

I have an array declared in my header file like this:

int snapshot[kSnapshotSize];

我真的很喜欢在实现文件中这样初始化:

which I would really love to init like this in my implementation file:

snapshot[kSnapshotSize] = {[0 ... kSnapshotSize-1] = 5};

但是编译器抱怨:期望的表达式"

however the compiler complains: "Expected expression"

有人可以告诉我我在做什么错吗?

Can anyone tell me what I'm doing wrong?

更新:int snapshot[kSnapshotSize] = {[0 ... kSnapshotSize] = 5};似乎有效,所以可能我缺少一些基本的知识.我想我可以使用memset,但首先要确保这是不可能的(为什么)

UPDATE: int snapshot[kSnapshotSize] = {[0 ... kSnapshotSize] = 5}; seems to work, so probably I'm missing something basic. I think I can use memset, but would first want to be sure this is not possible (and why)

更新2:正如许多人所指出的那样,似乎只有这样才能初始化一个数组,以后再填充.我最终使用了for循环.

UPDATE 2: As many of you pointed out, it seems that it's only possible to init an array like that not to populate it later. I end up using a for loop.

推荐答案

我想你的意思是

int snapshot[kSnapshotSize] = {[0 ... kSnapshotSize - 1] = 5};

但是...的使用是gcc特定的扩展.如果您不介意仅限于gcc,那就可以了.

But that use of ... is a gcc-specific extension. If you don't mind being limited to gcc, that's ok.

memset()无法正常工作;它将目标的每个 byte 设置为指定值.

memset() won't work; it sets each byte of the target to the specified value.

对于可移植性,最好的选择是使用一个显式循环来设置每个元素.

For portability, your best bet is to use an explicit loop to set each element.

这篇关于使用C中的单个值初始化数组(GCC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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