I have a program to create a matrix with initial values and then changing the matrix to given values.
(我有一个程序可以创建具有初始值的矩阵,然后将矩阵更改为给定值。)
But when I try to change the row count to a number equal to or larger than the initial value, the program crashes. (但是,当我尝试将行数更改为等于或大于初始值的数字时,程序崩溃。)
What am I doing wrong here? (我在这里做错了什么?)
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", *(*(arr +i ) + j));}
printf("
");}}
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;
}
ask by Luxeun translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…