我在C中有一个大数组(不是c++,如果这有区别的话)。我想初始化相同值的所有成员。
我发誓我曾经知道一个简单的方法。在我的情况下,我可以使用memset(),但没有一种方法来做到这一点,这是建立在C语法?
我在C中有一个大数组(不是c++,如果这有区别的话)。我想初始化相同值的所有成员。
我发誓我曾经知道一个简单的方法。在我的情况下,我可以使用memset(),但没有一种方法来做到这一点,这是建立在C语法?
当前回答
对于初始化“普通”数据类型(如int数组),你可以使用括号符号,但如果数组中仍有空格,它将把最后一个后面的值归零:
// put values 1-8, then two zeroes
int list[10] = {1,2,3,4,5,6,7,8};
其他回答
如果你想确保数组的每个成员都被显式初始化,只需从声明中省略维度:
int myArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
编译器将从初始化列表中推导出维度。不幸的是,对于多维数组,只有最外层的维度可能被省略:
int myPoints[][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9} };
还可以,但是
int myPoints[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9} };
不是。
如果数组恰好是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...
以防数组的大小发生变化。
对于延迟初始化(即类成员构造函数初始化),请考虑:
int a[4];
unsigned int size = sizeof(a) / sizeof(a[0]);
for (unsigned int i = 0; i < size; i++)
a[i] = 0;
没有人提到访问初始化数组元素的索引顺序。我的示例代码将为它提供一个说明性示例。
#include <iostream>
void PrintArray(int a[3][3])
{
std::cout << "a11 = " << a[0][0] << "\t\t" << "a12 = " << a[0][1] << "\t\t" << "a13 = " << a[0][2] << std::endl;
std::cout << "a21 = " << a[1][0] << "\t\t" << "a22 = " << a[1][1] << "\t\t" << "a23 = " << a[1][2] << std::endl;
std::cout << "a31 = " << a[2][0] << "\t\t" << "a32 = " << a[2][1] << "\t\t" << "a33 = " << a[2][2] << std::endl;
std::cout << std::endl;
}
int wmain(int argc, wchar_t * argv[])
{
int a1[3][3] = { 11, 12, 13, // The most
21, 22, 23, // basic
31, 32, 33 }; // format.
int a2[][3] = { 11, 12, 13, // The first (outer) dimension
21, 22, 23, // may be omitted. The compiler
31, 32, 33 }; // will automatically deduce it.
int a3[3][3] = { {11, 12, 13}, // The elements of each
{21, 22, 23}, // second (inner) dimension
{31, 32, 33} }; // can be grouped together.
int a4[][3] = { {11, 12, 13}, // Again, the first dimension
{21, 22, 23}, // can be omitted when the
{31, 32, 33} }; // inner elements are grouped.
PrintArray(a1);
PrintArray(a2);
PrintArray(a3);
PrintArray(a4);
// This part shows in which order the elements are stored in the memory.
int * b = (int *) a1; // The output is the same for the all four arrays.
for (int i=0; i<9; i++)
{
std::cout << b[i] << '\t';
}
return 0;
}
输出结果为:
a11 = 11 a12 = 12 a13 = 13
a21 = 21 a22 = 22 a23 = 23
a31 = 31 a32 = 32 a33 = 33
a11 = 11 a12 = 12 a13 = 13
a21 = 21 a22 = 22 a23 = 23
a31 = 31 a32 = 32 a33 = 33
a11 = 11 a12 = 12 a13 = 13
a21 = 21 a22 = 22 a23 = 23
a31 = 31 a32 = 32 a33 = 33
a11 = 11 a12 = 12 a13 = 13
a21 = 21 a22 = 22 a23 = 23
a31 = 31 a32 = 32 a33 = 33
11 12 13 21 22 23 31 32 33