二维数组和boost随机数生成器



我在我的程序中放入了两个循环-一个用一个值N0填充二维数组,下一个循环生成随机数。当我对数组进行循环时,我的程序无法工作。我得到"未处理的异常……"(参数:0 x00000003)"。但是没有第一个循环,它就能正常工作。谢谢你的帮助。

     #include <iostream>
#include <vector>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
using namespace std;

const double czas = 1E9;
int main()
{
    //Declaration of variables
    const int k = 20;
    const int L = 30;   
    double N0 = 7.9E9;
    int t,i,j, WalkerAmount;
    double excitation, ExcitationAmount;
    double slab[30][600];
    //Random number generator
    boost::random::mt19937 gen;
    boost::random::uniform_int_distribution<> numberGenerator(1, 4);

    //Filling slab with excitation
    for (int i = 0; i <= L; i++)
    {
        for (int j = 0; j <= k*L; j++) { slab[i][j] = N0; }
    }
    //Time loop
    for (t = 0; t < czas; t++) {
        WalkerAmount = 0;
        ExcitationAmount = 0;
        for (int i = 0; i <= L; i++)
        {
            for (int j = 0; j <= k*L; j++)
            {
                int r = numberGenerator(gen);
                cout << r << endl;
            }
        }
    }
    system("pause");
    return 0;
}

c++中的数组从0索引到n-1,其中n为数组的容量。那么,后面的代码是错误的。

int main()
{
    //Declaration of variables
    const int k = 20;
    const int L = 30;   
    double N0 = 7.9E9;
    double slab[30][600];
    // [...]
    for (int i = 0; i <= L; i++)
    {
        for (int j = 0; j <= k*L; j++) { slab[i][j] = N0; }
    }
}

初始化数组时,总是走得太远。当您考虑i == Lj == k*L的情况时,您到达了内存中超出数组的区域。

要执行的循环是

for (int i = 0; i < L; i++)
    for (int j = 0; j < k*L; j++)
        // Initialize

最新更新