问题描述
我写这应该realloc的每个输入数组的功能。我认为,功能效果很好,但是当我试图用我得到段错误的阵列的工作。
I wrote an function which should realloc the array for each input. I think that function works well, but when I'm trying to work with the array I got segmentation fault.
输入:
[1,2] [6,3] [2.5,3.5]
我要检查,如果用户以正确形式'['号','数']'
进入输入。我必须至少有2项。输入的到底是不是新的生产线,但EOF( CTRL + D 或 CTRL + 以Z )。
I have to check if the user enters input in the correct form '[' number ',' number ']'
. I have to have at least 2 entries. The end of input isn't new line, but EOF (+ or +).
我的code:
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;
}
而当我想用这样的:
And when I want to use this:
double min = sqrtf(powf(field[0][0] - field[1][0], 2) + powf(field[0][1] - field[1][1], 2));
我会得到我的分段错误。
I will get my segmentation fault.
推荐答案
从男人的realloc
(重点煤矿):
该realloc()的函数试图改变分配的大小指出
通过PTR大小,并返回PTR。如果没有足够的空间来
加大内存分配由ptr指向,的realloc()创建一个新的
分配,复制尽可能多的旧数据由ptr为适合
新的分配,释放旧的分配,并返回一个指针
分配的内存。
你不能保证,当你使用使用相同的内存的realloc
,你需要通过指针回的情况下,它的被移动到新位置。您可以通过检查它是否是一个空指针或没有,太检查成功。
You're not guaranteed to be using the same memory when you use realloc
, you need to pass the pointer back for the case that it's been moved to a new location. You can check for success by checking whether it's a NULL pointer or not, too.
TL;博士:您需要使用返回字段
而不是收益1
或返回0
。
tl;dr: You need to use return field
instead of return 1
or return 0
.
这篇关于用C的realloc双二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!