c++ - 数组 -> 另一个空 int 数组混淆

标签 c++ arrays int

考虑以下情况,您有两组数组 - 其中一组包含一组存储有值的整数,您可以将它们放入数组中并轻松计算数组中的值。但是,当您有一个包含空整数的数组时 - 它似乎无法将值“存储”到整数值 - 为什么?

这是一个例子:

int empty1;
int empty2;
int contain1 = 100;
int contain2 = 200;
int container [2] = { contain1, contain2 };
int empty_container [2] = { empty1, empty2 };
int i = 0;
while ( i != 2 ) {
    empty_container[i] = i;
    cout << endl << "empty_container[i]: " << empty_container[i] << endl
    << "empty1: " << empty1 << endl << "empty2: " << empty2 << endl;
    cout << "i: " << i << endl;
    cout << "container[i]: " << container[i] << endl;
    cout << "contain1: " << contain1 << endl;
    cout << "contain2: " << contain2 << endl;
    i++;
}

输出:

empty_container[i]: 0
empty1: 4197341
empty2: 0
i: 0
container[i]: 100
contain1: 100
contain2: 200

empty_container[i]: 1
empty1: 4197341
empty2: 0
i: 1
container[i]: 200
contain1: 100
contain2: 200

请注意,empty1 突然变为“4197341”,而empty2 变为 0,这是怎么回事?

UPD(来自评论):

我的意思是先声明一个整数,然后通过数组设置它 - 这对于 C++ 来说是不可能的吗?

最佳答案

因为您从未初始化过 empty1empty2 或为其赋值。 empty1empty2 没有全局或静态存储,它们不会被隐式初始化。它们都包含垃圾值。

您有未定义的行为。您可以看到,此编译器针对 empty1empty2 的值给出了不同的结果:Local variable not initialized Demo

始终记住在使用变量之前对其进行初始化。

编辑:

I mean like declaring an integer before and then set it through an array - is this not possible with C++?

恕我直言,你不能这样做。您可以使用给定的初始化变量来初始化数组元素。然而,你做了什么:

 int empty_container [2] = { empty1, empty2 };

不会使用该数组中的值将值分配给 empty1empty2,因为数组本身尚未初始化。

但是,您可以尝试以下操作:

empty_container[2] = {10}; //initialize array at first
empty1 = empty_container[0];
empty2 = empty_container[1]; //this will give you empty1 10 and empty2 0

在此处查看另一个现场演示:Array and Variable initialization demo

关于c++ - 数组 -> 另一个空 int 数组混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16848834/

相关文章:

c# - 如果不想读取整个字符串怎么办?

c++ - 用整数读取一行 C++

c - 将负数分配给 unsigned int 不会导致任何错误?

javascript - 使用 javaScript jQuery 对具有属性的关联数组进行排序

c - 在 typedef 结构中填充 int 数组时出错

c++ - 引用 STL vector 类型

c++ - 访问嵌套类中的空映射时发生访问冲突

c++ - C++ 中的 vector 与数组?

c++ - STL vector 插入 - 复制构造函数

c++ - 静态链接系统库、libc、pthreads,以帮助调试