动态调整矩阵大小会导致分段错误

时间:2016-12-03 10:18:12

标签: c

我想增加编码为双指针的矩阵的高度,但每次尝试时,我的代码都会出现段错误。我尝试了这个,但它不起作用:

void get_matrix_bigger(int ** matrix, int height, int width)
{
   int new_width, new_height, i;
   scanf("%d%d", &new_height, &new_width);

   matrix = realloc(matrix, new_height * sizeof(int *));
   for(i = height; i < new_height; i++)
       matrix[i] = malloc(new_width * sizeof(int));

}

int main(void)
{
   int ** matrix, height, width;
   scanf("%d%d", &height, &width);

   matrix = malloc(height * sizeof(int *));

   for(i = 0; i < height; i++)
       matrix[i] = malloc(width * sizeof(int));

   get_matrix_bigger(matrix, height, width);

   return 0;
}

1 个答案:

答案 0 :(得分:0)

在get_matrix_bigger函数中你应该传递***矩阵,否则你从get_matrix_bigger出来后你仍然在堆栈上有旧指针。

void get_matrix_bigger(int *** matrix, int height, int width)
{
   int new_width, new_height, i;
   scanf("%d%d", &new_height, &new_width);

   *matrix = realloc(*matrix, new_height * sizeof(int *));
   for(i = height; i < new_height; i++)
       *matrix[i] = malloc(new_width * sizeof(int));

}

并在main中使用它:

get_matrix_bigger(&matrix, height, width);