我是 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
}
如果您不知道如何使用标准容器,可以引用大量文档。