简体   繁体   English

为什么在 C++ 中未初始化数组中有随机数,而在半初始化数组的未初始化成员中没有?

[英]Why there are Random numbers in non initialized array but not in non initialized members of half initialized array in C++?

Why in example 1 code it assigns 0s in non initialized items of array, but in example 2 assigns random numbers in completely non initialized array?为什么在示例 1 代码中它在数组的未初始化项中分配 0,但在示例 2 中在完全未初始化的数组中分配随机数? Why it dont assign 0s to completely non initialized array as well?为什么它也不将 0 分配给完全未初始化的数组?

Example 1:示例 1:

int ar[5] ={0,1};
for (int i =0; i< 5; i++){
   cout << ar[i] << " ";
}
// output: 0 1 0 0 0 

Example 2:示例 2:

int ar[5] ;
for (int i =0; i< 5; i++){
   cout << ar[i] << " ";
}
// output: 1875998720 0 1875947552 0 1876031856 

They're two different initializations.它们是两种不同的初始化。

The case 2, int ar[5];情况2, int ar[5]; performs default initialization , as the effect all the elements are initialized to indeterminate values.执行默认初始化,因为所有元素都被初始化为不确定的值。

The case 1, int ar[5] ={0,1};情况1, int ar[5] ={0,1}; performs aggregate initialization , as the effect the 1st and 2nd element are initialized as 0 and 1 , the remaining elements are value-initialized (zero-initialized) as 0 .执行聚合初始化,因为第一个和第二个元素被初始化为01 ,其余元素的值初始化(零初始化)为0

In first Example !在第一个例子中! You are initializing the array of size 5 with default values.您正在使用默认值初始化大小为 5 的数组。

int arr[5] = {0,1}

values in curly braces will be assigned to the corresponding index in the array.花括号中的值将分配给数组中的相应索引。 For example 0 from at the first index of array, 1 at the second index and then default 0 values to the rest of the indexes in array.例如,数组的第一个索引为 0,第二个索引为 1,然后默认 0 值到数组中的其余索引。

In Second Example You are just declaring the array but not initializing.在第二个示例中,您只是声明了数组而不是初始化。 Therefor, at every index of the array, there is garbage value and when you iterate the array you receive unexcepted (garbage) value at each index of the array.因此,在数组的每个索引处,都有垃圾值,当您迭代数组时,您会在数组的每个索引处收到无例外(垃圾)值。

If you declare a variable but don't initialize with any value, it assign the random garbage value that we can't predict.如果你声明一个变量但没有用任何值初始化,它会分配我们无法预测的随机垃圾值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM