【发布时间】:2018-05-26 22:18:09
【问题描述】:
我必须在我的一个类中为一个项目实现一个函数,我在调整二维动态数组的尺寸时遇到了麻烦,表示为一个字符板。如果我将大小为 10 X 10 的板调整为较小的板,例如 5 X 5,则调整大小似乎可以正常工作并相应地截断数组。但是,如果我尝试增加电路板的大小,我会得到奇怪的结果或分段错误,我假设是因为 realloc 以某种方式失败了。任何反馈都会有所帮助;我正在尽我最大的努力理解指针,但我似乎无法在没有内存错误的情况下解决这个问题。在我正在编写的较大程序中,我有一个函数可以释放板的分配内存,但这里我主要关心的是我实现 realloc 的方式。
#include <stdio.h>
#include <stdlib.h>
char** constructBoard(int num_rows, int num_cols, char empty_space){
//this function dynamically allocates a matrix of chars
char** board = (char**)malloc(num_rows * sizeof(char*));
for(int row = 0; row < num_rows; ++row){
board[row] = (char*)malloc(num_cols * sizeof(char));
for(int col = 0; col < num_cols; ++col){
board[row][col] = empty_space;
}
}
return board;
}
void displayBoard(char** board, const int num_rows, const int num_cols){
//this function prints out the board
int rowNum = num_rows - 1;
for(int row = 0; row < num_rows; ++row){
if(num_rows - row <= 10) {
printf(" ");
printf("%d ", rowNum);
}
else{
printf("%d ", rowNum);
}
rowNum = rowNum - 1;
for(int col = 0; col < num_cols; ++col){
printf(" %c", board[row][col]);
printf(" ");
}
printf("\n");
}
printf(" ");
for(int i = 0; i < num_cols; ++i){
if(i == 0){
printf(" %d", i);
printf(" ");
}
else if(i < 10) {
printf(" %d", i);
printf(" ");
}
else{
printf("%d", i);
printf(" ");
}
}
printf("\n");
}
void resizeBoard(char*** board, int new_num_row, int new_num_col, int* num_rows, int* num_cols){
//this function is supposed to resize the dimensions of the board without causing memory leaks
(*board) = realloc(*board, (new_num_row * sizeof(char*)));
for(int y = *num_rows; y < new_num_row; ++y){
(**board)[y] = '*';
}
for(int x = 0; x < new_num_row; ++x){
(*board)[x] = realloc((*board)[x], new_num_col * sizeof(char));
}
*num_rows = new_num_row;
*num_cols = new_num_col;
}
int main() {
char empty_space = '*';
int num_rows = 5;
int num_cols = 5;
char** board;
int new_num_row = 7;
int new_num_col = 7;
board = constructBoard(num_rows, num_cols, empty_space);
displayBoard(board, num_rows, num_cols);
resizeBoard(&board, new_num_row, new_num_col, &num_rows, &num_cols);
return 0;
}
【问题讨论】:
-
这里没有二维数组。当您不检查
realloc()返回的值时,为什么您认为realloc()失败了?当您发现自己使用 3 颗星时,请考虑重新考虑程序设计。
标签: c multidimensional-array dynamic-arrays realloc