C / C ++未初始化数组的结果 [英] C/C++ the result of the uninitialized array
问题描述
这可能是一个无聊的问题!谢谢!
It might be a boring question! thanks!
这是代码:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int a[5] = {0};
int b[5];
cout << a << endl;
cout << b << endl;
for (int i = 0; i < 5; i++)
{
cout << a[i] << " ";
}
cout << endl;
for (int i = 0; i < 5; i++)
{
cout << b[i] << " ";
}
cout << endl;
return 0;
}
在Ubuntu中:g ++ a.cpp
in Ubuntu: g++ a.cpp
在装有DEV C ++的Windows中,MinGW GCC 4.7.2:
< a href = https://i.stack.imgur.com/QoNZw.png rel = nofollow noreferrer>
In windows with DEV C++ ,MinGW GCC 4.7.2:
因此,问题集中在数组b上:
So the question is focused on the array b:
>我知道我还没有初始化数组b。
I know I haven't initialized the array b.
数组b充满了垃圾值,但是为什么总是在固定位置使用 0,例如 X 0 X 0 X ??
Array b is full of garbage values, but why there is always having '0' with the fixed position like "X 0 X 0 X"??
里面发生了什么???
只是一种保护机制?
What happens inside?? Just a protection mechanism?
推荐答案
这是未定义的行为。如果存在这些零,则不能保证只是偶然。
That is undefined behavior. There is no guarantee, if these zeros are there, that just accidentally is true.
解释是,由于某种随机原因,在内存中的这些位置存储了0。在将其重新用于您的目的之前。由于您是在堆栈上分配数组,因此这些零可能来自先前的函数调用,并且可能有些填充。编译器将按照他的意愿进行操作。
The explanation is, that for some random reason at these places in memory a 0 was stored before it was reused for your purpose here. Since you allocate your arrays on the stack, these zeroes are probably from a prior function call and might be some padding. The compiler will do that as he pleases.
这篇关于C / C ++未初始化数组的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!