-2

我目前正在做一个项目,我正在平均最后 10 到 20 次测量的输出。为此,我将最后 10 个值保存在一个数组中。右移元素以更新数据。

我用来转移值的代码:

void shiftvals() {
    memmove(&val[1], &val[0], (sizeof(val) / sizeof(val[0]))-1);
    for (unsigned int i = 0; i < (sizeof(val) / sizeof(val[0])); i++)
    {
        Serial.print(val[i]);
        Serial.print(",");
    }
    Serial.println();
}

调用函数的代码:

#define ARR_SIZE 10
uint16_t val[ARR_SIZE];

void loop(){
    Serial.print("Size of the array:\t");
    Serial.println(sizeof(val) / sizeof(val[0]));

    shiftvals();

    val[0] = (analogRead(A0));
}

现在的问题是最后几个输出将始终为 0,即使数组很好地填满。当我增加数组的大小时,空格的数量也会增加。

输出:

396,396,381,462,503,195,0,0,0,0,
472,472,396,381,462,247,0,0,0,0,
495,495,472,396,381,206,0,0,0,0,
435,435,495,472,396,125,0,0,0,0,

我很困惑,我做错了memmove什么?

4

2 回答 2

2

问题出在您对 memmove 的调用中。你的尺码太短了。

void shiftvals() {
    memmove(&val[1], &val[0], (sizeof(val) / sizeof(val[0]))-1);

    // that was only 9 bytes, but val[] is 20 bytes long.

    // ...
}

应该读

void shiftvals() {
    memmove(&val[1], &val[0], (ARR_SIZE - 1) * sizeof(val[0]));
    // ...
}
于 2017-07-10T10:48:16.093 回答
2

用 C++ 的方式来做:

#include <iostream>
#include <array>
#include <algorithm>

std::array<int,10> val = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

void shiftVals()
{
  std::rotate( begin(val), end(val)-1, end(val));
}

int main()
{
  shiftVals();
  for(auto v: val ) std::cout << v << " ";
  std::cout << "\n";
}

考虑使用全局变量。

于 2017-07-10T10:59:19.007 回答