【问题标题】:returning dynamically created array from function从函数返回动态创建的数组
【发布时间】:2021-09-27 22:08:57
【问题描述】:

我正在尝试将 pq 公式的解决方案作为动态创建的数组返回。 这样做的正确方法是什么? 这是我的功能:

double *pq (double a, double b)
{
 double x1=(-1)*(a/2)-sqrt((a/2)*(a/2)-b);
 double x2=(-1)*(a/2)+sqrt((a/2)*(a/2)-b);
 double *arr[]=(double *)malloc(2*sizeof(double));
 arr[2]={{x1}, {x2}};

 return arr;

}

另外,为什么我在arr[2]={{x1}, {x2}}; 上收到“预期的表达式”错误?

我的主要功能:

    int main ()
{
    double *arr[2]={0}, a=0.00, b=0.00;

    scanf("%lf %lf", a,b);

    if ((a*a)-(b*a)>=0)
    {
        for (int i=0; i<2; i++)
        {
            arr[i] = pq(a,b);
        }   
    }

    else
    {
        printf("Es gibt keine reellen L\224sungen.");
    }
 
    for (int i=0; i<2;i++)
    {
        printf("%lf", arr[i]);
    }


    return 0;
}

【问题讨论】:

  • 您的 arr 变量类型错误,即使更正,您也会破坏您的数组(索引是从零开始的,所以 [1] 是长度为 2 的数组的最大索引)。
  • 考虑返回一个结构体,其中包含两个双精度数组和一个整数,用于计算实际解决方案的数量,并完全避免动态分配。

标签: c dynamic-memory-allocation dynamic-arrays return-type function-definition


【解决方案1】:

而不是这些行

 double *arr[]=(double *)malloc(2*sizeof(double));
 arr[2]={{x1}, {x2}};

 return arr;

你需要在函数pq内写

double *arr = malloc( 2 * sizeof( double ) );

if ( arr != NULL )
{
    arr[0] = x1;
    arr[1] = x2;
}

return arr;

main

double *arr = NULL;
double a = 0.0, b = 0.0;

scanf("%lf %lf", &a, &b );
                 ^^^^^^
if ((a*a)-(b*a)>=0)
{
    arr = pq( a, b );
}
else
{
    printf("Es gibt keine reellen L\224sungen.");
}

if ( arr != NULL )
{
    for (int i=0; i<2;i++)
    {
        printf( "%f", arr[i] );
                 ^^^
    }
}

free( arr );

【讨论】:

    【解决方案2】:

    你不能初始化这样一个动态分配的数组en bloc。相反,依次为每个元素赋值。通过对函数进行一些重新排序,您甚至可以消除对中间变量(x1x2)的需求:

    double *pq (double a, double b)
    {
        double *arr = malloc(2*sizeof(double)); // No need to cast!
        arr[0] = (-1)*(a/2)-sqrt((a/2)*(a/2)-b);
        arr[1] = (-1)*(a/2)+sqrt((a/2)*(a/2)-b);
        return arr;
    }
    

    关于malloc函数的返回值的转换,参见:Do I cast the result of malloc?

    另外,您必须更改main 函数的工作方式;不要声明本地数组并在调用后尝试分配数据;只需使用函数返回的“数组”,因为元素的值已经存在:

    int main ()
    {
        double a=0.00, b=0.00;
    
        scanf("%lf %lf", &a, &b); // Note the address (&) operators!
    
        if ((a*a)-(b*a)>=0)
        {
            double *arr = pq(a, b);
            for (int i=0; i<2; i++)
            {
                printf("%lf", arr[i]);
            }
            free(arr); // Don't forget to free the memory!
        }
        else
        {
            printf("Es gibt keine reellen L\224sungen.");
        }
        return 0;
    }
    

    【讨论】:

      【解决方案3】:

      问题出在这一行

      arr[2]={{x1}, {x2}};
      

      arr[2] = 正在分配给数组的第三个元素,该元素超出范围。而且您不能使用该大括号语法来分配给这样的数组切片。而是

      arr[0] = x1;
      arr[1] = x2;
      

      【讨论】:

      • double *arr[] 也没有给他们任何好处。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      相关资源
      最近更新 更多