c++ - 不能将 float 数组传出函数

标签 c++ arrays floating-point

<分区>

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

这是我的代码。我希望 readSensor() 函数传递一个由 3 个 float 组成的 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;
}

最佳答案

您不能按照您寻求的方式“将数组传递出函数”。 C++ 没有通过简单地使用指针和原始(C 风格)数组提供这种机制。

在你的特定方法中

void readSensor(float* output) {
 float container[3] = {val1, val2, val3};
 output = container;
}

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];
}

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

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

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

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
}

如果您不知道如何使用标准容器,可以引用大量文档。

关于c++ - 不能将 float 数组传出函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56310367/

相关文章:

c++ - NSIS System::Call - 调用方法失败

java - 在二维数组中查找相邻元素并计算它们。

c++ - 100 万数组中的 C/C++ Stackoverflow 错误

c++ - 如何在C++中写小数点后两位数?

c - 用 C 语言编写浮点乘法函数

c++ - 错误推回对 const vector 元素的引用

C++ 在指向 char 数组指针的指针上使用 strcpy_s()

C 将 float 转换为整数

javascript - 如何使用 WebKit 在 JavaScript 中调用 C++ 函数?

javascript - 如何在 React 中将所有数组项重新排序到特定索引?