-3

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?

6
  • 9
    Please refrain from posting images of text. Commented Sep 6, 2016 at 14:42
  • 1
    @HIPPO LD you already know the answer "Array b is full of garbage values" Commented Sep 6, 2016 at 14:44
  • Sorry I am just a rookie..Maybe it is a real boring question! Commented Sep 6, 2016 at 14:48
  • @n.m. sorry I am new here and new in programming so I don't know the rules.. Commented Sep 6, 2016 at 14:50
  • 2
    Ignorantia legis non excusat! Please edit your question to comply to site-rules! And don't add C tag for C++ questions! They are different languages. Commented Sep 6, 2016 at 14:57

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

The behaviour on reading uninitialised elements of an array is undefined. The compiler is allowed to do anything.

(All the elements of a can be read due to the brace initialisation, although in C++ you can write int a[5] = {};).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.