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

问题描述 投票:-2回答:1

[试图构建菜单系统,但遇到一些指针问题-我经验不足。

我不明白为什么删除while(1)会使mainmenu_table [1] [i] ==&option6之间的比较失败,但是由于某种原因,它确实如此。

我做错了什么?使用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()
{

}
c++ arduino atmega
1个回答
2
投票

根据Arduino对PROGMEM的描述,您不能像使用普通指针一样直接通过指向它的指针访问数据。您需要使用proper macros/functions来访问数据。

在您的代码中,指针表本身位于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) {
    //...

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

© www.soinside.com 2019 - 2024. All rights reserved.