Reallocation of contiguous 2D array

淺唱寂寞╮ 提交于 2019-12-08 11:14:37

The first malloc and the memcpy are unnecessary, because you have easy access to the original data array at ptr_array[0]. You don't need to know the old size, because realloc should recall how much it allocated at the address and move the correct ammount of data.

Something like this should work.

double **
reallocate_double_array (double **ptr_array, int count_row_new, int count_col)
{
  int i;
  int new_size = count_row_new * count_col;

  double *data = ptr_array[0];
  data = realloc (data, new_size * sizeof (double));

  free (ptr_array);

  ptr_array = calloc (count_row_new, sizeof (double *));

  for (i = 0; i < count_row_new; i++)
    ptr_array[i] = data + (i * count_col);

  return ptr_array;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!