【发布时间】:2019-06-06 07:22:26
【问题描述】:
我的目标是将指向 double 的指针传递给函数,在函数内部动态分配内存,用 double 值填充结果数组并返回填充数组。在 StackOverflow 中到处潜伏后,我发现了两个相关的主题,分别是 Initializing a pointer in a separate function in C 和 C dynamically growing array。因此,我尝试编写自己的代码。但是,结果与上述主题中描述的不同。该程序使用 gcc 和 Visual Studio 运行。
一审。
int main()
{
double *p;
int count = getArray(&p);
<...print content of p...>
return 0;
}
int getArray(double *p)
{
int count = 1;
while(1)
{
if(count == 1)
p = (double*)malloc(sizeof(double));
else
p = (double*)realloc(p, count*sizeof(double));
scanf("%lf", &p[count-1]);
<...some condition to break...>
count++;
{
<... print the content of p ...>
return count;
}
(这是来自编译器的关于参数类型不兼容的警告。忽略它)。
输入:
1.11
2.22
3.33
输出:
1.11
2.22
3.33
0.00
0.00
0.00
二审。
int main()
{
double *p;
int count = getArray(&p);
<...print content of p...>
return 0;
}
int getArray(double **p)
{
int count = 1;
while(1)
{
if(count == 1)
*p = (double*)malloc(sizeof(double));
else
{
double ** temp = (double*)realloc(*p, count*sizeof(double));
p = temp;
}
scanf("%lf", &(*p)[count-1]);
<...some condition to break...>
count++;
{
<... print the content of p ...>
return count;
}
输入:
1.11
2.22
Segmentation error.
我在几台不同的 *nix 机器上尝试过这种方法,当循环使用 realloc 时它会失败。令人惊讶的是,这段代码使用 Visual Studio 可以完美运行。
我的问题是:第一个代码允许分配和重新分配内存,甚至将所有分配的内存传递给 main(),但是,所有值都归零。问题是什么?至于第二个程序,分割错误的原因是什么?
【问题讨论】:
-
if(count = 0)你的意思是if(count == 0)?您的编译器是否发出任何警告?它可能会给你一个警告。 -
为什么“把戏”没用?除非有你没有提到的东西,否则它正是你问题的正确解决方案。
-
@Blaze,对不起“==”运算符。至于其他部分,编译器没有警告。
-
@rtoijala,这就是我的代码中的全部内容。没有其他功能或操作。
-
@tenghiz 使用双指针是正确的方法。