简体   繁体   English

在函数中修改动态2D数组

[英]Modifying a dynamic 2D array in a function

I've got a function that accepts a dynamic multidimensional array (which is initialized to 0) as a parameter, and I'm trying to modify certain values within the array in my function. 我有一个函数可以接受动态多维数组(已初始化为0)作为参数,并且正在尝试在函数中修改数组中的某些值。

The function that accepts the array as a parameter is supposed to simulate the roll of two dice and output the frequency distribution to the array I made that's initialized to zero. 接受数组作为参数的函数应该模拟两个骰子的滚动,并将频率分布输出到我制作的初始化为零的数组。

The code for it is as follows: 其代码如下:

#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";
    }

}

Code works for me with just a few issues (I had to guess how you defined a . Next time add that too): 代码对我来说只有几个问题(我不得不猜测您a如何定义。的,下一次也要添加它):

In the printing you should print a space after every number (minor) 在打印时,您应该在每个数字(小数)后打印一个空格

In the random, you choose index as 1+rand()%6 , so from 1 to 6, but when you print you take indexes from 0 to 5! 在随机中,将index选择为1+rand()%6 ,因此从1到6,但是在打印时,索引从0到5! So your first row and first column will be 0. 因此,您的第一行和第一列将为0。

Other than that it seems to work. 除此之外,它似乎还可以。

Only when one goes and does something else does the answer come to mind. 只有当一个人去做别的事情时,答案才会浮现在脑海。 I suspect you declared a as: 我怀疑您声明为:

int a[6][6];

which is an array of 36 integers. 这是36个整数的数组。 In your function, though, you're declaring rollarray to be a pointer to an array of pointers to integers. 但是,在函数中,您要声明rollarray为指向整数的指针数组的指针。 All you need to do is change the function signature to: 您需要做的就是将函数签名更改为:

int* rollDie(int numRolls, unsigned short seed, int* rollarray)

As cluracan said, you also want to use array indices in the range 0 to 5. 正如cluracan所说,您还想使用0到5范围内的数组索引。

This is a good case for either the judicious use of print statements or stepping through with a debugger to see what's really going on. 对于明智地使用print语句或逐步调试程序以查看实际情况,这是一个很好的例子。

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

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