我在C中有一个大数组(不是c++,如果这有区别的话)。我想初始化相同值的所有成员。

我发誓我曾经知道一个简单的方法。在我的情况下,我可以使用memset(),但没有一种方法来做到这一点,这是建立在C语法?


当前回答

如果数组恰好是int或int大小的任何东西,或者你的mempattern的大小恰好符合int的精确时间(即全部为零或0xA5A5A5A5),最好的方法是使用memset()。

否则,在循环中调用memcpy()移动索引。

其他回答

int i;
for (i = 0; i < ARRAY_SIZE; ++i)
{
  myArray[i] = VALUE;
}

我觉得这比

int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5...

以防数组的大小发生变化。

如果你的编译器是GCC,你可以使用以下“GNU扩展”语法:

int array[1024] = {[0 ... 1023] = 5};

查看详细描述: http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Designated-Inits.html

这里有另一种方法:

static void
unhandled_interrupt(struct trap_frame *frame, int irq, void *arg)
{
    //this code intentionally left blank
}

static struct irqtbl_s vector_tbl[XCHAL_NUM_INTERRUPTS] = {
    [0 ... XCHAL_NUM_INTERRUPTS-1] {unhandled_interrupt, NULL},
};

See:

c扩展

指定的初始化

然后问这个问题:什么时候可以使用C扩展?

上面的代码示例是在嵌入式系统中,永远不会从其他编译器中看到。

除非该值为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,指向空值,等等)

我知道最初的问题明确地提到了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中)