Bil*_*lie 15 c function multidimensional-array
我创建了一个生成宾果板的功能,我想要返回宾果板.
正如我没想到的那样,它不起作用.
这是功能:
int** generateBoard() {
int board[N][M], i, j , fillNum;
Boolean exists = True;
// initilize seed
srand(time(NULL));
// fill up..
for(i = 0; i < N; ++i) {
for(j = 0; j < M; ++j) {
exists = True;
while(exists) {
fillNum = rand()%MAX_RANGE + 1; // limit up to MAX_RANGE
if(beenAdded(board, fillNum) == Exist) {
continue;
} else {
board[i][j] = fillNum;
exists = False;
}
}
}
}
return board;
}
Run Code Online (Sandbox Code Playgroud)
我在"返回板"行有一个compilcation错误(红色子行).
有没有使用结构\动态分配返回2D数组的方法?
我正在使用Microsoft Visual C++ Express 2010.
Isr*_*man 16
您定义board
为局部变量 - 当函数超出范围时,其内存将被处理.
您可以将板声明为全局,或者您可以动态创建它,如下所示:
int **allocate_board(int Rows, int Cols)
{
// allocate Rows rows, each row is a pointer to int
int **board = (int **)malloc(Rows * sizeof(int *));
int row;
// for each row allocate Cols ints
for (row = 0; row < Rows; row++) {
board[row] = (int *)malloc(Cols * sizeof(int));
}
return board;
}
Run Code Online (Sandbox Code Playgroud)
您需要动态释放电路板:
// you must supply the number of rows
void free_board(int **board, int Rows)
{
int row;
// first free each row
for (row = 0; row < Rows; row++) {
free(board[row]);
}
// Eventually free the memory of the pointers to the rows
free(board);
}
Run Code Online (Sandbox Code Playgroud)
Who*_*aig 13
有人必须在某处拥有该板的内存,更重要的是,所有权必须延伸回该函数的调用者.如果没有动态分配,您唯一的其他替代方法是将其发送到函数中,如in/out参数.
void generateBoard(size_t N, size_t M, int board[N][M])
{
int i, j , fillNum;
Boolean exists = True;
// initilize seed
srand(time(NULL));
// fill up..
for(i = 0; i < N; ++i) {
for(j = 0; j < M; ++j) {
exists = True;
while(exists) {
fillNum = rand()%MAX_RANGE + 1; // limit up to MAX_RANGE
if(beenAdded(board, fillNum) == Exist) {
continue;
} else {
board[i][j] = fillNum;
exists = False;
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
并从你的调用者调用这样的:
int main()
{
const size_t N = 10;
const size_t M = 10;
int board[N][M];
generateBoard(N,M,board);
...
}
Run Code Online (Sandbox Code Playgroud)
我还会考虑重新srand()
调用启动代码的调用main()
.理想情况下,它应该永远不会出现在一些可能重复调用的函数中,并且应该保证每个进程执行只执行一次.(注意:老实说,我不记得每个线程是否执行一次,但是在你的编码学习曲线的这一点上,我猜多线程还没有出现在雷达上).
最后,你的随机填充循环是不必要的重复.有更好的替代方案可以生成您正在尝试做的事情:创建现有数字集的随机排列.正如所写,你可以旋转一段时间,试图填补最后几个插槽,具体取决于与之MAX_RANGE
相比的大小(N*M)
.