为什么我得到这种输出,因为我知道数组中未初始化的整数元素的默认值是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?

本文关键字:初始化 整数 元素 默认值 数组 我知道 因为 输出 为什么      更新时间:2023-10-16
#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类型的数组元素(如intvoid *struct some_standard_c_structure)的函数作用域的初始值未定义。ar2满是垃圾

staticglobal作用域的数组元素的初始值是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初始化为该数字。