我有一个程序可以创建具有初始值的矩阵,然后将矩阵更改为给定值。但是,当我尝试将行数更改为等于或大于初始值的数字时,程序崩溃。我在这里做错了什么?
void fill(int row, int column, int **arr){
int k = 0;
for(int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
*(*(arr + i)+j) = k;
k++;}}}
void print(int row, int column, int **arr){
for(int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
printf("%d\t", *(*(arr +i ) + j));}
printf("\n");}}
int **create(int row, int column){
int **arr = (int **)malloc(row * sizeof(int *));
for (int i=0; i<row; i++){
*(arr + i) = (int *)malloc(column * sizeof(int));}
return arr;}
int** modify(int oldRowCount, int row, int column, int **arr){
arr =(int **) realloc(arr,(unsigned long) row * sizeof (int **));
for(int i = 0; i < row; i++)
*(arr + i) =(int *) realloc(*(arr+i),(unsigned long) column * sizeof (int));
if(oldRowCount <= row){
for (int i = oldRowCount; i < row; i++)
*(arr + i) = (int *)malloc(column * sizeof(int));
}
else{
for(int i = row + 1; i <= oldRowCount; i++)
free(*(arr + i));
}
return arr;}
int main()
{
int row = 4;
int column = 4;
int oldRowCount=row;
int **arr = create(row,column);
fill(row, column, arr);
print(row, column, arr);
while(1){
oldRowCount = row;
scanf("%d",&row);
scanf("%d",&column);
arr = modify(oldRowCount, row, column, arr);
fill(row, column, arr);
print(row, column, arr);
}
return 0;
}
最佳答案
之所以这样,是因为realloc()尝试重新分配空内存。例如,如果新行计数= 6,则当i = 4时,重新分配尝试将重新分配指针指向无处。在这种情况下,arr也应作为参考接受。
void modify(int row, int column, int oldRowCount, int** &arr) {
arr = (int **)realloc(arr, row * sizeof(int*));
for (int i = 0; i < oldRowCount; i++) {
*(arr + i) = (int *)realloc(*(arr + i), column * sizeof(int));
}
for (int i = oldRowCount; i < row; i++) {
*(arr + i) = (int *)malloc(column * sizeof(int));
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
*(*(arr + i) + j) = 0;
}
}
}