简体   繁体   中英

Last array printing 0 C++

I'm making a dice game in C++, and in my program I have some arrays.

die[5] = { (rand()%6)+1, (rand()%6)+1, (rand()%6)+1, (rand()%6)+1, (rand()%6)+1 };

And then I use the arrays with

cout<<"First die: "<< die[0] <<"\n"

etc

But, when I run the program, the last array will always print 0, is there a way I can fix this?

You're not really giving much information, but here's my guess:

  • You're stepping too far. The last spot in the array is die[4], and chances are you're using die[5], which means you're accessing memory you're not supposed to. On some systems, this will automatically initialize as "0".

Arrays of size N always include N elements ranging from 0 to N-1. Using array[N] accesses memory beyond the range of the array. This could be unused memory (best case) or memory assigned to something else. The result is TROUBLE. Do not do this.

In your code you have this line:

54.  cout<<"Sixth die: " << die[5] <<"\n";

which is an invalid access as die has only 5 elements thus 0 to 4 are valid indexes.

This is actually "undefined behaviour". Your program might core-dump / give an access violation but it doesn't have to. It can instead just output some random number or zero...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM