初始化一个整数数组 [英] initializing an array of ints

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

问题描述

有没有人可以简单地将 int 数组(任何多字节类型都可以)初始化为非零和非 -1 值?我的意思是,有没有办法在一个班轮中做到这一点,而不必单独执行每个元素:

Does anyone have a way to initialize an array of ints (any multi-byte type is fine really), to a non-zero and non -1 value simply? By which I mean, is there a way to do this in a one liner, without having to do each element individually:

int arr[30] = {1, 1, 1, 1, ...}; // that works, but takes too long to type

int arr[30] = {1}; // nope, that gives 1, 0, 0, 0, ...

int arr[30];
memset(arr, 1, sizeof(arr)); // That doesn't work correctly for arrays with multi-byte
                             //   types such as int

仅供参考,在静态数组上以这种方式使用 memset() 给出:

Just FYI, using memset() in this way on static arrays gives:

arr[0] = 0x01010101
arr[1] = 0x01010101
arr[2] = 0x01010101

另一种选择:

for(count = 0; count < 30; count++)
   arr[count] = 1;    // Yup, that does it, but it's two lines.

有人有其他想法吗?只要是 C 代码,解决方案就没有限制.(其他库都可以)

Anyone have other ideas? As long as it's C code, no limits on the solution. (other libs are fine)

推荐答案

这是一个 GCC 扩展:

This is a GCC extension:

int a[100] = {[0 ... 99] = 1};

这篇关于初始化一个整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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