为什么我得到这种输出,因为我知道数组中未初始化的整数元素的默认值是0
Why am i getting this kind of output since i know that the default values of non-initialized integer elements of an array is 0?
#include <iostream>
using namespace std;
void RemoveZeroElements(int arr1[],int arr2[],int &i){
int n=0;
int m=0;
while(n<14) {
switch(arr1[n]) {
case 0:
n+=1;
break;
default:
arr2[m]=arr1[n];
m+=1;
n+=1;
i+=1;
break;
}
}
}
int main()
{
int ar1[14]={2,4,5,0,7,-9,0,0,11,23,44,0,13,999};
int ar2[14];
int efsize=0;
RemoveZeroElements(ar1,ar2,efsize);
cout<<"the new array without the zeros has an effective size of "<< efsize << endl;
for (int i=0;i<14;i++) {
if(ar2[i]!=0) {
cout << "the new array has its " << (i+1)<< "th element set to " <<
ar2[i]<< endl;
}
}
}
得到的输出如下:
the new array without the zeros has an effective size of 10
the new array has its 1th element set to 2
the new array has its 2th element set to 4
the new array has its 3th element set to 5
the new array has its 4th element set to 7
the new array has its 5th element set to -9
the new array has its 6th element set to 11
the new array has its 7th element set to 23
the new array has its 8th element set to 44
the new array has its 9th element set to 13
the new array has its 10th element set to 999
the new array has its 11th element set to 1
the new array has its 12th element set to 65535
the new array has its 13th element set to 4308980
the new array has its 14th element set to -1079890440
问题出在第12,13,14个元素
你知道的是错的。POD类型的数组元素(如int
、void *
、struct some_standard_c_structure
)的函数作用域的初始值未定义。ar2
满是垃圾
0
(不考虑多线程问题)
你必须确保在使用ar2
之前清除它的内容。最简单的方法是使用std::fill()
:
std::fill(ar2, ar2 + (sizeof(ar2) / sizeof(int)), 0);
在C语言中,等效的是memset()
:
memset(ar2, 0, sizeof(ar2));
因为你错了。这些都是未初始化的值,可以是任何值。如果它们是静态存储持续时间对象,而不是自动存储持续时间对象,它们将被初始化为零。最好不要考虑它,总是初始化变量。
您在这里所做的是将ar2的前十个元素设置为ar1中不为零的数字。你的问题元素不只是12、13、14号,还包括11号。您会注意到数字1也不在原始数组中。
最后四个元素不是零,它们是完全未声明的,因为他在上面说了^^。如果您希望ar2为ar1而不包含零,只需在for循环中执行计数,计算有多少元素不为零,并将ar2初始化为该数字。
相关文章:
- C++使用整数的压缩数组初始化对象
- 整数在VSCommunity2019,windows10中未初始化
- 为什么初始化 std::vector 时不能使用模板整数?
- 在标头中C++整数初始化
- 初始化不是整数的巨大常量多维数组的最佳方法是什么?
- 如何初始化整数+字符串数组
- 如何将整数重新初始化/设置为空值
- 使用整数初始化列表初始化长双精度的向量
- 当 map 是一个整数数组并且由 operator[] 创建时,它是否初始化其映射类型
- 使用 size_t 初始化循环变量时的整数下溢
- C++11 整数初始化
- 错误 C2864:'element::next':只能在类 (STRUCT) 中初始化静态常量整数数据成员
- 错误:调用'begin(long double [nPoints])'没有匹配函数;使用硬编码的 int 与整数变量初始化向量
- 如何初始化无符号整数uint8_t
- 如何使用整数列表在LLVM中初始化整数数组
- 初始化整数成员变量会导致更改另一个成员变量的地址
- 初始化整数的隔离错误
- 为什么在C++类中只能初始化整数或枚举类型
- memset如何以-1初始化整数数组
- 位集限制,如何在C++中运行时初始化整数