在 C 中用单个值初始化数组 (GCC)
我在头文件中声明了一个数组,如下所示:
int snapshot[kSnapshotSize];
我真的很想在实现文件中像这样初始化:
snapshot[kSnapshotSize] = {[0 ... kSnapshotSize-1] = 5};
但是编译器抱怨:“预期表达式”
任何人都可以告诉我我做错了什么吗?
更新: int snapshot[kSnapshotSize] = {[0 ... kSnapshotSize] = 5};
似乎有效,所以我可能错过了一些基本的东西。我想我可以使用memset,但首先要确定这是不可能的(以及为什么)
更新2:正如你们许多人指出的那样,似乎只能初始化一个像这样的数组以免稍后填充它。我最终使用了 for 循环。
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?
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)
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想你的意思是
但是
...
的使用是 gcc 特定的扩展。如果您不介意仅限于 gcc,那也没关系。memset()
不起作用;它将目标的每个字节设置为指定值。为了可移植性,最好的选择是使用显式循环来设置每个元素。
I presume you mean
But that use of
...
is a gcc-specific extension. If you don't mind being limited to gcc, that's ok.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.