c++ - 在函数中修改动态二维数组

标签 c++ dynamic-arrays

我有一个接受动态多维数组(初始化为 0)作为参数的函数,我试图在我的函数中修改数组中的某些值。

接受数组作为参数的函数应该模拟两个骰子的滚动并将频率分布输出到我制作的初始化为零的数组。

它的代码如下:

#include <iostream>
#include <cstdlib>

using namespace std;

int** rollDie(int numRolls, unsigned short seed, int** &rollarray)
{
srand(seed);
int side1, side2;
while (numRolls > 0)
{
side1 = 1 + rand() % 6;
side2 = 1 + rand() % 6;

rollarray[side1][side2]++;

numRolls--;
}
return rollarray;

}

int** initializeArray(void)
{
    int i, j;
    int** m = new int*[6];

    for (i = 0; i < 6; i++)
        m[i] = new int[6];

    for (i = 0; i < 6; i++)
        for (j = 0; j < 6; j++)
            m[i][j] = 0;

    return m;
}

int main()
{
int numRolls;
unsigned short seed;
int ** a = initializeArray();


cout << "rolls?\n";
cin >> numRolls;

cout << "seed?\n";
cin >> seed;
int ** b = rollDie(numRolls, seed, a);

int i,j;
for (i = 0; i < 6; i++) {
    for (j = 0; j < 6; j++) {
        cout << b[i][j];
    }
    cout << "\n";
    }

}

最佳答案

代码对我来说只有几个问题(我不得不猜测你是如何定义 a 的。下次也添加它):

在打印中你应该在每个数字(次要)之后打印一个空格

在随机中,您选择索引作为 1+rand()%6,所以从 1 到 6,但是当您打印时,您选择索引从 0 到 5!因此,您的第一行和第一列将为 0。

除此之外,它似乎还有效。

关于c++ - 在函数中修改动态二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17736553/

相关文章:

C++ 列表从位置删除元素并将其放在末尾

C++ 二进制文件 io

C 数组行为 - 全局/局部/动态

c++ - 如何找到导致 "malloc(): memory corruption: 0x00"的行

C++:以对角线方式处理二维数组元素

c++ - CPU_ONLY 构建 : compiling the function Forward() gives error "undefined reference..."

c - 如何在C中创建一个随机二维数组,其值仅重复两次

返回对象时清除 C++ 动态数组

c++ - SIGSEGV 同时尝试读取数组

c - 调整数组大小后出现段错误