【发布时间】:2012-11-08 18:15:41
【问题描述】:
有没有人有办法将ints 的数组(任何多字节类型都可以)简单地初始化为非零和非-1 值?我的意思是,有没有办法在一个班轮中做到这一点,而不必单独执行每个元素:
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() 给出:
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 代码,解决方案就没有限制。 (其他库都可以)
【问题讨论】:
-
有 wmemset() 用于“宽”字符数组
-
其他库不需要>1行吗?
#include libother -
@MarcB - 还不错......两个小问题,首先我了解
wchar_t is compiler-specific and can be as small as 8 bits,所以这可能是单字节。其次,我希望有一些可以在不同类型上工作的东西。但不是一个坏建议。谢谢。 -
Mac OS X 自 10.5 版起具有
memset_pattern4()、memset_pattern8()和memset_pattern16()。 -
@mcalex - Touché。好的,“每个设置 1 班轮”怎么样,我们不会将
#includes或更多选项计入gcc
标签: c arrays initialization