初始化数组、"memset"或" {//value} "的最佳方法是什么?

which is best way to initialize array, "memset" or " {//value} "?

本文关键字:最佳 方法 是什么 value memset 数组 初始化      更新时间:2023-10-16
int main(){
int ar[50]={1};
//OR
int br[50];
memset(br, 1, sizeof(br)); 
return 0;
}
int ar[50]={1};

这将仅将第一个元素设置为1。其余的都将0.

memset(br, 1, sizeof(br));

这会将br中的所有字节设置为 1。这与将所有值设置为1不同。之后的值为:

{16843009, 16843009, 16843009, 16843009, 16843009}

当您知道自己确实需要memset时,请使用它。它并不完全是为了初始化数组而制作的,它只是将内存设置为特定值。

C++的最佳方式?使用std::fillstd::fill_n

例:

int array[5];
std::fill(array, array + 5, 8);

数组现在包含:

{8, 8, 8, 8, 8}

使用fill_n

std::fill_n(array, 5, 99);

数组现在包含:

{99, 99, 99, 99, 99}

作为旁注,更喜欢使用std::array而不是 c 样式数组。

试穿神电:https://godbolt.org/z/DmgTGE

参考资料:
[1] : 数组初始化
[2] : 内存集文档

假设你这样做

int ar[50] = {-1};

现在你会期望这一行用 -1 初始化所有数组元素 但事实并非如此。它只会将数组的第一个元素设置为 -1,将 rest 设置为 0。 而 memset 将显示预期的行为。

有关详细信息,请参阅此将数组的所有元素初始化为C++中的一个默认值?

让我们举个例子:-

int arr[5] = { 1, 2 }; // this will initialize to 1,2,0,0,0

int ar[5] = {  }; // this will  initialize  all elements 0

int myArray[10] = {}; // his will also all elements 0 in C++ not in c

因此,如果要将特定值初始化为数组,请使用memset((。

如果要将数组中的所有元素初始化为 0,请使用

static int myArray[10]; // all elements 0

因为如果未指定初始值设定项,具有静态存储持续时间的对象将初始化为 0,并且它比 memset(( 更具可移植性。

此外,int ar[50]={0};将是无限的,因为它只是初始化数组并且没有结尾,但memset(arr,0,sizeof(br))它具有结束数组循环的正确方法