2

I am new to C++. Recently, I have been stuck with a simple code of C++ features. I will be very grateful if you can point out what exactly the problem. The code as follows:

// used to test function of fill
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
   int val = 0;
   int myarray[8];
   //fill(myarray,myarray+2,1);
   for(;val < 8;++val){
      cout << myarray[val];
      cout << endl;
      }
}

And the it has printed out:

-887974872
 32767
 4196400
 0
 0
 0
 4196000
 0

The question is I thought the default value for array without initialization (in this case its size is 8) would be (0,0,0,0,0,0,0,0). But there seemed to be some weird numbers there. Could anyone tell me what happened and why?

3
  • 3
    This should sum up why they aren't zeroed: chat.stackoverflow.com/transcript/message/10771489#10771489 Commented Jul 23, 2013 at 2:25
  • local variables are not default initialized Commented Jul 23, 2013 at 2:28
  • I thought the default value for array without initialization (in this case its size is 8) would be (0,0,0,0,0,0,0,0). What made you assume that? (I just mean, lets not assume lets play safe and stick to what the doc says) Commented Jul 23, 2013 at 8:41

4 Answers 4

11

The elements are un-initialized, i.e, they contain garbage value.

If you want to initialize the array elements to 0, use this:

int myarray[8] = {};
Sign up to request clarification or add additional context in comments.

1 Comment

@nicknguyen128, if you accept his answer, please click the checkmark by the number. This gives him a little reputation bump, and it marks it as the answer for any who find your question and learn from it.
1

Initial values are not guaranteed to be 0.

2 Comments

I would add that setting the DEBUG flag on some of the the MSVC compilers will include their debug run time libraries which DO initialize values, but the RELEASE run time libraries do NOT initialize them. It can be the source of frustration if you're not careful.
I often wish the debug libraries would initialize to random numbers instead of zeros to avoid that
1

If you want to get a array have a initial value,you can do like this:

int *arr = new int[8]();

Comments

0
int myarray[8];

This is a simple declaration of an Array i.e you are telling the compiler "Hey! I am gonna use an integer array of size 8". Now the compiler knows it exists but it does not contail any values. It has garbage values.

If you intend to initialize array (automatically) then you need to add a blank initialization sequence.

int myarray[8]={}; //this will do

Happy Coding!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.