DrOnline
DrOnline

Reputation: 741

int array gives crazy values unless all fields initialized to 0, why?

int TwoThrows();


int main(){

        int Throws, Throw, Frequency[13]={0,0,0,0,0,0,0,0,0,0,0,0,0};
        randomize();


        cout << "\nThis program simulates throws of two dice.";
        cout << "\n\nHow many throws : ";
        cin >> Throws;



        // Calls TwoThrows and saves in Frequency by value
        for(int I=0; I<Throws; I++){
                Throw=TwoThrows();   //2-12
                Frequency[Throw]++;   //2-12

        }

         // Prints array:
        for(int I=0; I<11; I++){
                cout << I+2 << ":\t" << Frequency[I+2] << "\n";

        }

        return 0;
}

int TwoThrows(){
        unsigned int I=(random(6)+1)+(random(6)+1);

        return I;

}

This prints:

2: 1317 3: 2724 4: 4145 5: 5513 6: 7056 7: 8343 8: 6982 9: 5580 10: 4176 11: 2776 12: 1388

Which is great.

However, what I want to know is, why did I have to set the array to {0,0,0,0,0,0,0,0,0,0,0,0,0}?

If I do NOT do that; i get:

2: 30626868 3: 1638233 4: 844545295 5: 1 6: 9 7: 4202510 8: 4199197 9: 844555757 10: 3 11: 4202574 12: 2130567168

Upvotes: 1

Views: 321

Answers (4)

LiaqatG
LiaqatG

Reputation: 367

Try to understand it this way. All memory locations are charged and when we assign a specific memory location to a variable, it will translated the raw value that the location was holding, also referred to as garbage value and hence we get unexpected values.

But when you initialize a variable or array, the default garbage values are replaced with the designated values and we get the desired output.

Hope this helps.

Upvotes: 1

Alyafey
Alyafey

Reputation: 1453

When you allocate an array you got place in memory so this place could be used before by anther application,So if don't initialize that place it would give you unexpected values according to which application was using that place.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

Local variables are put on the stack of the function. This area is not initialized by the compiler or the operating system. This means that the values of local variables are exactly what's in the memory when the function is called, which is unlikely to be something you want it to be.

Upvotes: 2

NPE
NPE

Reputation: 500297

If you don't initialize the array, and then proceed to increment its elements, technically this is undefined behaviour.

What happens in practice is that the array's elements get whatever values happen to be on the stack when main() starts.

Upvotes: 3

Related Questions