c - 在 C 中重新分配双二维数组

标签 c malloc coordinates multidimensional-array realloc

我写了一个函数,它应该为每个输入重新分配数组。我认为该函数运行良好,但当我尝试使用数组时出现段错误。

输入:

[1,2] [6,3] [2.5,3.5]

我必须检查用户输入的格式是否正确'['number','number']'。我必须至少有 2 个条目。输入的结尾不是新行,而是 EOF(CTRL+DCTRL+Z)。

我的代码:

double ** allocation (double ** field, int i)
{
   double x = 0, y = 0;
   char obr[1], cbr[1], col[1];

   while (scanf("%c%lf%c%lf%c", &obr, &x, &col, &y, &cbr) == 5)
   {
       if (col[0] != ',' || obr[0] != '[' || cbr[0] != ']')
           return 0;

       field = (double **) realloc(field, (i + 1) * sizeof(*field));
       if (field == NULL)
           return 0;

       field[i] = (double *)malloc(2 * sizeof(double));
       if (field[i] == 0)
           return 0;

       field[i][0] = x;
       field[i][1] = y;
       i++;
  }
  if (feof (stdin))
      return 0;

  return field;
}

当我想使用它时:

double min = sqrtf(powf(field[0][0] - field[1][0], 2) + powf(field[0][1] - field[1][1], 2));

我会得到我的段错误。

最佳答案

来自man realloc(强调我的):

The realloc() function tries to change the size of the allocation pointed to by ptr to size, and returns ptr. If there is not enough room to enlarge the memory allocation pointed to by ptr, realloc() creates a new allocation, copies as much of the old data pointed to by ptr as will fit to the new allocation, frees the old allocation, and returns a pointer to the allocated memory.

当您使用 realloc 时,您不能保证使用相同的内存,您需要将指针传回,以防它已移动到新位置。您也可以通过检查它是否为 NULL 指针来检查是否成功。

tl;dr:您需要使用 return field 而不是 return 1return 0

关于c - 在 C 中重新分配双二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20299034/

相关文章:

java - 显示鼠标坐标的标签

android - 计算Android屏幕上两点之间的路径

r - R中圆上等距n个点的坐标?

c - 多字符字符常量 [-Werror,-Wmultichar]

c - DEV C++ 头文件列表

c - 需要帮助来理解 free() 函数在 C 中的工作原理

c++ - 能不调用构造函数就调用析构函数吗?

c - 解析用户输入的两个值

指针符号的 C 解释?

c - 找出 valgrind 提出的问题