我在C中有一个大数组(不是c++,如果这有区别的话)。我想初始化相同值的所有成员。
我发誓我曾经知道一个简单的方法。在我的情况下,我可以使用memset(),但没有一种方法来做到这一点,这是建立在C语法?
我在C中有一个大数组(不是c++,如果这有区别的话)。我想初始化相同值的所有成员。
我发誓我曾经知道一个简单的方法。在我的情况下,我可以使用memset(),但没有一种方法来做到这一点,这是建立在C语法?
当前回答
我知道最初的问题明确地提到了C而不是c++,但如果你(像我一样)来这里寻找c++数组的解决方案,这里有一个巧妙的技巧:
如果你的编译器支持fold表达式,你可以使用template magic和std::index_sequence生成一个包含你想要的值的初始化列表。你甚至可以把它想象成一个老板:
#include <array>
/// [3]
/// This functions's only purpose is to ignore the index given as the second
/// template argument and to always produce the value passed in.
template<class T, size_t /*ignored*/>
constexpr T identity_func(const T& value) {
return value;
}
/// [2]
/// At this point, we have a list of indices that we can unfold
/// into an initializer list using the `identity_func` above.
template<class T, size_t... Indices>
constexpr std::array<T, sizeof...(Indices)>
make_array_of_impl(const T& value, std::index_sequence<Indices...>) {
return {identity_func<T, Indices>(value)...};
}
/// [1]
/// This is the user-facing function.
/// The template arguments are swapped compared to the order used
/// for std::array, this way we can let the compiler infer the type
/// from the given value but still define it explicitly if we want to.
template<size_t Size, class T>
constexpr std::array<T, Size>
make_array_of(const T& value) {
using Indices = std::make_index_sequence<Size>;
return make_array_of_impl(value, Indices{});
}
// std::array<int, 4>{42, 42, 42, 42}
constexpr auto test_array = make_array_of<4/*, int*/>(42);
static_assert(test_array[0] == 42);
static_assert(test_array[1] == 42);
static_assert(test_array[2] == 42);
static_assert(test_array[3] == 42);
// static_assert(test_array[4] == 42); out of bounds
您可以查看工作中的代码(在Wandbox中)
其他回答
除非该值为0(在这种情况下,可以省略初始化式的某些部分 并且相应的元素将被初始化为0),没有简单的方法。
不过,不要忽视显而易见的解决方案:
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
缺少值的元素将初始化为0:
int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0...
所以这将把所有元素初始化为0:
int myArray[10] = { 0 }; // all elements 0
在c++中,空初始化列表也会将每个元素初始化为0。 C在C23之前是不允许的:
int myArray[10] = {}; // all elements 0 in C++ and C23
记住,如果没有,具有静态存储持续时间的对象将初始化为0 初始化式被指定:
static int myArray[10]; // all elements 0
而“0”并不一定意味着“全位零”,所以使用上面的是 比memset()更好、更可移植。(浮点值将是 初始化为+0,指向空值,等等)
对于初始化“普通”数据类型(如int数组),你可以使用括号符号,但如果数组中仍有空格,它将把最后一个后面的值归零:
// put values 1-8, then two zeroes
int list[10] = {1,2,3,4,5,6,7,8};
我看到了一些使用这种语法的代码:
char* array[] =
{
[0] = "Hello",
[1] = "World"
};
它变得特别有用的地方是当你创建一个使用枚举作为索引的数组时:
enum
{
ERR_OK,
ERR_FAIL,
ERR_MEMORY
};
#define _ITEM(x) [x] = #x
char* array[] =
{
_ITEM(ERR_OK),
_ITEM(ERR_FAIL),
_ITEM(ERR_MEMORY)
};
这使事情保持有序,即使您碰巧把一些枚举值写成了无序的顺序。
关于这项技术的更多信息可以在这里和这里找到。
用0初始化
char arr[1000] = { 0 };
最好使用普通的“for循环”来进行除0以外的初始化。
char arr[1000];
for(int i=0; i<arr.size(); i++){
arr[i] = 'A';
}
对于静态初始化具有相同值的大型数组,不需要多次复制粘贴,你可以使用宏:
#define VAL_1X 42
#define VAL_2X VAL_1X, VAL_1X
#define VAL_4X VAL_2X, VAL_2X
#define VAL_8X VAL_4X, VAL_4X
#define VAL_16X VAL_8X, VAL_8X
#define VAL_32X VAL_16X, VAL_16X
#define VAL_64X VAL_32X, VAL_32X
int myArray[53] = { VAL_32X, VAL_16X, VAL_4X, VAL_1X };
如果需要更改值,则只能在一个位置进行替换。
编辑:可能有用的扩展
(乔纳森·莱弗勒提供)
你可以很容易地概括这一点:
#define VAL_1(X) X
#define VAL_2(X) VAL_1(X), VAL_1(X)
/* etc. */
可以使用以下命令创建变量:
#define STRUCTVAL_1(...) { __VA_ARGS__ }
#define STRUCTVAL_2(...) STRUCTVAL_1(__VA_ARGS__), STRUCTVAL_1(__VA_ARGS__)
/*etc */
这适用于结构或复合数组。
#define STRUCTVAL_48(...) STRUCTVAL_32(__VA_ARGS__), STRUCTVAL_16(__VA_ARGS__)
struct Pair { char key[16]; char val[32]; };
struct Pair p_data[] = { STRUCTVAL_48("Key", "Value") };
int a_data[][4] = { STRUCTVAL_48(12, 19, 23, 37) };
宏名称可以协商。