简体   繁体   English

最后数组打印0 C ++

[英]Last array printing 0 C++

I'm making a dice game in C++, and in my program I have some arrays. 我正在用C ++制作骰子游戏,在我的程序中我有一些数组。

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? 但是,当我运行程序时,最后一个数组将始终显示 0,有什么办法可以解决此问题?

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. 数组中的最后一个点是die [4],很可能您正在使用die [5],这意味着您正在访问不应该使用的内存。 On some systems, this will automatically initialize as "0". 在某些系统上,这将自动初始化为“ 0”。

Arrays of size N always include N elements ranging from 0 to N-1. 大小为N的数组始终包含N个元素,范围从0到N-1。 Using array[N] accesses memory beyond the range of the array. 使用array [N]会访问超出数组范围的内存。 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. 这是无效的访问,因为die仅具有5个元素,因此0到4是有效索引。

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... 它可以只输出一些随机数或零...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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