c++ - Arduino 结构变量似乎在没有明确重新分配的情况下被重新分配

标签 c++ variables struct arduino

<分区>

我正在尝试使用 Arduino IDE 为控制按钮的对象使用结构。

我为 fillAndFire.pin 值分配了一个值 14。

fillAndFire.pin    = 14;

稍后,代码将值重新分配为零,但它不应该。

displayLine[i] = displayLine[i-1];

完整代码:

char* displayLine[15];

struct Buttons{
  int pin;
  int lightPin;
  bool io;
  bool pressed;
  uint8_t* bName;
} fillAndFire;

void setup() {

  //start Serial service
  Serial.begin(9600);
  while (!Serial){
    delay(1);
  }

  //define pin
  fillAndFire.pin    = 14;

  //message 1 gives a value of 14
  Serial.print("fillAndFire.pin 1 = ");Serial.println(fillAndFire.pin);

  //mysteriously, this changes the value of Buttons fillAndFire.pin from 14 to 0
  //if I change the 15 to 14, it does not affect the fillAndFire.pin variable. 
  //other numbers, like "1" works just fine, but not 2, 3 or 14
  //even other assignments, like "fillAndFire.lightpin = 14" works?!?!?!
   displayLine[15] = displayLine[13];

  //message 4 gives a value of 0, 
  //but it has not be explicitly reassigned
  Serial.print("fillAndFire.pin 4 = ");Serial.println(fillAndFire.pin);
}

void loop() {
}

最佳答案

我不知道是否有以下影响,但看起来你有一个 15 长度的 char* vector ,即 displayLine[0..14],并且在赋值的 for 循环中,在第一次迭代中会出现一个不存在的 displayLine[15]。在计算机中它应该导致段错误,但在 Arduino 中可能是原因。试试 for(int i = 14; ...)

关于c++ - Arduino 结构变量似乎在没有明确重新分配的情况下被重新分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54355400/

相关文章:

c++ - std::map 使用比较参数检查第一个和第二个值

c++ - 静态库中命名空间内简单函数的编译错误

variables - 常量和静态变量有什么区别,我应该选择哪个?

c - 在此 C 程序中返回结构时出错的原因是什么?

c# - 如果一个结构不能继承另一个类或结构,为什么 Int32 有 ToString() 方法?

php - 登录后通过 session 设置变量

c++ - 如何使模板类的一个实例与同一模板的另一个实例成为 friend

c++ - 当定义为模板参数时,编译器如何推断数组大小?

c++ - 如何动态确定libudev版本

arrays - BASH:将 $1 评估为字符串以调用数组长度