c++ - 简单的 C++ 程序超出其数组边界并崩溃

标签 c++ arrays random

我是 C++ 新手。我想生成要在我的程序中使用的随机字符串序列。它大部分时间都有效,但偶尔会出现异常并从计算机内存中转储随机字符串。我犯了什么愚蠢的错误(如果有的话)?

代码如下:

#include <iostream>
#include <ctime> // Needed for the true randomization
#include <cstdlib>
#include <string>

using namespace std;

int main ()
{
    string holder[] = {"A", "B", "C", "D", "E"};

    int xRan;
    srand(time(0)); // This will ensure a really randomized number by help of time.

    xRan=rand()%6+1;
    xRan--;
    cout << "Value of xRan is: " << xRan << " value is " << holder[xRan] << endl;   

    return 0;
}

最佳答案

您的 xRan 计算为您提供了 1 到 6 之间的数字。您的数组有 5 个元素,它们的编号为 0 到 4。

xRan=rand() % 6 + 1; 更改为 xRan=rand() % 5;,然后删除递减 的下一行>xRan。这将为您提供 0 到 4 之间的数字,这就是您想要的。

关于c++ - 简单的 C++ 程序超出其数组边界并崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22509224/

相关文章:

javascript - 给定一个整数数组 ‘num’ 返回该数组加 1

python - 从python中的类列表中随机选择x个项目

python - 随机模块不工作。值错误 : empty range for randrange() (1, 1、0)

c++ - 每次arduino启动时如何防止颜色数组成为相同的随机数组

javascript - .push() 问题

C++ 基本 while 循环,通过按键退出

c++ - 从 5 个加扰的序列中导出有序序列

c++ - Qt QTreeWidget 一项一项添加

c++ - 使用 C++ 进行复制省略和运算符重载

Python - "comparison"将一个数组映射到另一个数组的简单方法