Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

It might be a boring question! thanks!

Here's the code:

#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;
}

in Ubuntu: g++ a.cpp

enter image description here

In windows with DEV C++ ,MinGW GCC 4.7.2: enter image description here

So the question is focused on the array b:

I know I haven't initialized the array b.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

That is undefined behavior. There is no guarantee, if these zeros are there, that just accidentally is true.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...