【发布时间】:2019-11-30 11:03:19
【问题描述】:
我有一个程序来创建一个具有初始值的矩阵,然后将矩阵更改为给定值。但是当我尝试将行数更改为等于或大于初始值的数字时,程序崩溃了。我在这里做错了什么?
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;
}
【问题讨论】:
-
即使在修复该问题之后,如果
row变化增加,那么您重新分配现有行的枚举将使用arr[i]插槽,之前没有分配实际行,但仍将它们的值传递给 @ 987654325@。如果它在 decrease 上发生变化,您将从孤立的行中泄漏内存。孩子们,这就是为什么动态数组在包含当前大小分配限制的结构中进行管理。 -
arr =(int **) realloc(arr,(unsigned long) row * sizeof (int **));。arr是函数本地的。您所做的是释放原始的arr,然后分配一个新块,该块在函数退出时丢失。也就是说,在modify中的代码之后,随后的fill调用会传递一个已被释放的arr。 -
我不明白为什么 arr 是一个局部变量,即使我传递了它的地址@kaylum
-
modify(row, column, arr);不会将arr的地址传递给函数。arr的地址是&arr。在 C 中,所有函数参数都是按值传递的。 -
“即使我传递了地址” - 你没有传递 指针的地址;您正在将地址 in 传递给指针(即它的值)。更简洁地说,如果
p是一个指针类型的arg,那么p =在调用方方面不会发生任何变化;*p = ...确实如此。您可以通过使用modify的其他未使用结果来避免成为 a 3-star programmer,就像您在更新的代码中一样。我提醒您阅读我的第一条评论。它暴露了一个主要的设计缺陷,您需要重新评估您计划如何解决该问题。