我在C中有一个大数组(不是c++,如果这有区别的话)。我想初始化相同值的所有成员。
我发誓我曾经知道一个简单的方法。在我的情况下,我可以使用memset(),但没有一种方法来做到这一点,这是建立在C语法?
我在C中有一个大数组(不是c++,如果这有区别的话)。我想初始化相同值的所有成员。
我发誓我曾经知道一个简单的方法。在我的情况下,我可以使用memset(),但没有一种方法来做到这一点,这是建立在C语法?
当前回答
没有人提到访问初始化数组元素的索引顺序。我的示例代码将为它提供一个说明性示例。
#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
其他回答
如果数组声明为静态或全局,则所有元素 在数组中已经有默认默认值0。 一些编译器在调试模式中将array的默认值设置为0。 将默认值设置为0很容易: Int数组[10]= {0}; 但是,对于其他值,您必须使用memset()或loop;
例子: int数组[10]; Memset(数组,- 1,10 *sizeof(int));
如果你的编译器是GCC,你可以使用以下“GNU扩展”语法:
int array[1024] = {[0 ... 1023] = 5};
查看详细描述: http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Designated-Inits.html
如果数组恰好是int或int大小的任何东西,或者你的mempattern的大小恰好符合int的精确时间(即全部为零或0xA5A5A5A5),最好的方法是使用memset()。
否则,在循环中调用memcpy()移动索引。
作为Clemens Sielaff回答的后续。这个版本需要c++ 17。
template <size_t Cnt, typename T>
std::array<T, Cnt> make_array_of(const T& v)
{
return []<size_t... Idx>(std::index_sequence<Idx...>, const auto& v)
{
auto identity = [](const auto& v, size_t) { return v; };
return std::array{identity(v, Idx)...};
}
(std::make_index_sequence<Cnt>{}, v);
}
你可以在这里看到它的作用。
#include<stdio.h>
int main(){
int i,a[50];
for (i=0;i<50;i++){
a[i]=5;// set value 5 to all the array index
}
for (i=0;i<50;i++)
printf("%d\n",a[i]);
return 0;
}
它将给o/p 5 5 5 5 5 5 ......直到整个数组的大小