【问题标题】:Error cannot convert 'float*' to 'float' in return错误无法将“float*”转换为“float”作为回报
【发布时间】:2020-08-18 18:31:01
【问题描述】:

我是 C++ 新手,我正在尝试了解数组在函数中的行为。这是一种矩阵向量乘法的尝试。

#include <stdio.h>

#define N 4
float Gi[N][N] = {{ 0.0,         0.0,         0.0,         1.0},
                  { 0.0,  2.57142857,  3.42857143,  1.28571429},
                  {-0.0,  3.42857143,  8.57142857,  1.71428571},
                  { 1.0,  1.28571429,  1.71428571,  0.14285714}};

void mult(
        float vec_I[N],
        float vec_V[N]){
    int acc;
    for(int i = 0; i<N; i++){
        acc = 0;
        for(int j = 0; j<N; j++){
            acc += Gi[i][j]*vec_I[j];
            }
        vec_V[i] = acc;
    }
}

float solver(){
    float out[N];

    float I[N] = {0.0, 0.0, 0.0, 10.0};
    float V[N] = {0.0, 0.0, 0.0, 0.0};

    mult(I, V);
    
    out[0] = V[0];
    out[1] = V[1];
    out[2] = V[2];
    out[3] = V[3];
    return out;
}

int main(){
    float outPrint[4];

    outPrint = solver();

    printf("| %d |\n", outPrint[0]);
    printf("| %d |\n", outPrint[1]);
    printf("| %d |\n", outPrint[2]);
    printf("| %d |\n", outPrint[3]);

    return 0;
}

当我尝试编译时,编译器告诉我“[Error] cannot convert 'float*' to 'float' in return”,关于求解器函数的返回(第 34 行)。我不明白为什么。

【问题讨论】:

  • 你想让solver返回什么?一个数字,还是一个数字数组?看起来你打算让它返回一个数组
  • std::array&lt;float, 4&gt; 替换所有数组会很容易解决这个问题
  • 但也要问自己,“我是否要返回一个即将超出范围并变为无效的局部变量?”
  • 正确使用newmalloc 涉及很多心理开销,而且通常需要大量调试,因此更喜欢使用a library container,例如std::array上面Mooing Duck提到的。专家们不会碰newmalloc 或任何其他手动管理的动态分配,除非他们必须这样做,你也不应该这样做。
  • 或者只是通过引用将数组传递给函数并以这种方式修改它。让外界担心范围:)

标签: c++ arrays function


【解决方案1】:

数组不是一等公民。因此,它们不能按价值返回。您将不得不像这样使用结构包装器:

struct matrix_t
{
  float data[16];
};

【讨论】:

  • 结构解决方案完美运行。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多