无法将浮点数组传递出函数

Ste*_*102 1 c++ arrays floating-point

我是c ++的新手,我想使用指针将float数组传递出函数。但是,返回的数组始终为0;我在Arduino Uno上运行。

这是我的代码。我希望readSensor()函数传递一个包含3个float的float数组。浮点数组应传递给指针输出*。但是,当我打印出读数时,它显示的是0.00,而不是我传递的值。

void setup() {
  Serial.begin(9600);
}

void loop() {
  float readings[3];
  readSensor(readings);
  for (int i = 0;i < 3;i++) {
    Serial.println(readings[i]);
  }
  delay(1000);
}

// pass out these 3 floats
float val1 = 3.14159;
float val2 = 2.741;
float val3 = 87;
void readSensor(float* output) {
  float container[3] = {val1, val2, val3};
  output = container;
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*ter 5

您无法按照自己的方式“将数组从函数中传递出去”。C ++仅通过使用指针和原始(C样式)数组就没有提供这种机制。

在您的特定方法中

void readSensor(float* output) {
 float container[3] = {val1, val2, val3};
 output = container;
}
Run Code Online (Sandbox Code Playgroud)

container函数返回时,它不再存在。另外,output按值传递,因此分配output = container对调用者不可见。

必须将指向数组(数组的第一个元素)的指针传递给函数,并让函数根据需要将数据复制到该数组。例如,

void readSensor(float* output)
{
     float container[3] = {1, 2, 3};
     for (int i = 0; i < 3; ++i)
        output[i] = container[i];
}
Run Code Online (Sandbox Code Playgroud)

并且调用者必须提供数组并传递它。

int main()
{
     float result[3];
     readSensor(result);   // data will be copied into result
     // use result here
}
Run Code Online (Sandbox Code Playgroud)

请记住,调用者负责正确调用该函数。例如,如果上面函数的调用者传递了一个包含两个元素的数组,则该行为是不确定的。

C ++中的一种首选方法是使用标准容器,例如std::vector。例如;

#include <vector>

std::vector<float> readSensor()
{
     float container[3] = {1, 2, 3};
     std::vector<float> output;
     for (int i = 0; i < 3; ++i)
        output.push_back(container[i]);
     return output;
}

int main()
{
     std::vector<float> result;
     result = readSensor();
     // use result here
}
Run Code Online (Sandbox Code Playgroud)

如果您不知道如何使用标准容器,则周围有很多文档。

  • @FrançoisAndrieux-是的,是的。但是,这个问题显然是初学者提出的。而且该语法看起来像是在返回数组,即使它做的事情大不相同(使用初始化程序列表构造向量并返回该数组)。 (2认同)