删除while(1)时,指针到指针的比较中断-为什么



试图构建一个菜单系统,但遇到了一些指针问题——我对此没有太多经验。

我不明白为什么删除while(1(会导致mainmenu_table[1][I]==&备选方案6,但出于某种原因确实如此。

我做错了什么?使用visual studio和atmega328p。感谢

带原始代码的串行输出:

Serial begins
MeNu6
MeNu6
Starting compare loop
it worked

移除while(1(时具有的串行输出。

Serial begins
MeNu6
MeNu6
Starting compare loop
the end

原始代码(包含while(1((

const char option1[] PROGMEM = "Menu1";
const char option2[] PROGMEM = "MEnu2";
const char option3[] PROGMEM = "MeNu3";
const char option4[] PROGMEM = "Menu4";
const char option5[] PROGMEM = "MEnu5";
const char option6[] PROGMEM = "MeNu6";
const char option7[] PROGMEM = "menu7";
const char* const submenu1_table[] PROGMEM = { option1, option2, option3 }; // array of pointers to chars stored in flash
const char* const submenu2_table[] PROGMEM = { option4, option5, option6, option7 };
const char** const mainmenu_table[] PROGMEM = { submenu1_table, submenu2_table }; //array of pointers to pointers to chars in flash

// The setup() function runs once each time the micro-controller starts
void setup()
{
Serial.begin(9600);
delay(100);
Serial.println("Serial begins");  
Serial.println((const __FlashStringHelper*)(mainmenu_table[1][2]));  // prints "Menu6" as expected
Serial.println((const __FlashStringHelper*)option6);  // also prints "Menu6"
Serial.println("Starting compare loop");
for (int i = 0; i < 4; i++) {
if ( mainmenu_table[1][i] == &option6 ) { //
Serial.println("it worked");
while (1);  // COMMENTING THIS OUT MEANS DOESN'T COMPARE SUCCESSFULLY.
}
}
Serial.println("the end");
}
// Add the main program code into the continuous loop() function
void loop()
{
}

根据Arduino对PROGMEM的描述,您不能像使用普通指针那样直接通过指向数据的指针来访问数据。您需要使用适当的宏/函数来访问数据。

在您的代码中,指针表本身位于PROGMEM中,因此,要提取各个指针,您应该执行以下操作:

const char** submenu = (const char**)pgm_read_word(&(mainmenu_table[1]));
const char* option = (const char*)pgm_read_word(&(submenu[i]));
if (option == option6) {
//...

此代码基于第一个链接中的字符串表示例。

最新更新