Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

c - initializing an array of ints

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

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

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

The other option:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a GCC extension:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...