2013-11-28 87 views
1

我正在研究一個問題,我認爲這個問題基本上可以通過一個(多個)鏈表來解決。然而,我的平臺是一個非常有限SRAM的Arduino,所以我想將它全部保存在PROGMEM中(使用avr/pgmspace.h庫)。在PROGMEM(Arduino)中製作一個鏈表

我在引用結構體的字段時遇到了問題,我有一個指針。或者換一種說法,我在鏈接列表中遇到問題。

下面是一些代碼(我試圖讓它短):

#include <avr/pgmspace.h> 

typedef struct list_item 
{ 
    const prog_char * header; 
    const struct list_item *next_item; 
}; 

// declarations 
extern const list_item PROGMEM first_item; 
extern const list_item PROGMEM second_item; 
extern const list_item PROGMEM third_item; 

// name 
const prog_char first_header[] PROGMEM = "Foo"; 
const prog_char second_header[] PROGMEM = "Bar"; 
const prog_char third_header[] PROGMEM = "Baz"; 

// instantiation & initialization 
const list_item first_item = { &first_header[0], &second_item }; 
const list_item second_item = { &second_header[0], &third_item }; 
const list_item third_item = { &second_header[0], &first_item }; 

// pointers to our items, just for testing 
list_item const * const pointer_to_first_item = &first_item; 
list_item const * const pointer_to_second_item = &second_item; 
list_item const * const pointer_to_third_item = &third_item; 

// prints the address of the pointer passed to it 
void print_pointer_address(char * description, const void * pointer) 
{ 
    Serial.print(description); 
    Serial.println((unsigned int) pointer,HEX); 
} 

// a test 
void setup() 
{ 
    Serial.begin(57600); 

    Serial.println("\n--addresses of everything--"); 

    print_pointer_address("pointer to first_item = ", pointer_to_first_item); 
    print_pointer_address("pointer to second_item = ", pointer_to_second_item); 
    print_pointer_address("pointer to third_item = ", pointer_to_third_item); 

    Serial.println("\n--go through list via pointers--"); 

    list_item const * the_next_item; 
    the_next_item = pointer_to_first_item; 
    print_pointer_address("item 1 = ", the_next_item); 

    the_next_item = the_next_item->next_item; 
    print_pointer_address("item 2 = ", the_next_item); 

    the_next_item = the_next_item->next_item; 
    print_pointer_address("item 3 = ", the_next_item); 

    the_next_item = the_next_item->next_item; 
    print_pointer_address("item 4 = ", the_next_item); 

} 

void loop() 
{ 
} 

它輸出:

--addresses of everything-- 
pointer to first_item = 68 
pointer to second_item = 6C 
pointer to third_item = 70 

--go through list via pointers-- 
item 1 = 68 
item 2 = 6C 
item 3 = 1 
item 4 = 5350 

我的問題是:爲什麼第3項不等於 「70」?

我想可能是,我應該使用pgmspace函數來讀取結構,但後來我不明白爲什麼它似乎適用於第一項。感謝您提供任何幫助或指示,我應該閱讀以理解這一點。

回答

1

好的,解決了。獲得PROGMEM中結構字段指針的正確方法是:

the_next_item = (list_item*) pgm_read_byte(&(the_next_item->next_item)); 

我當然感到困惑。另外,它似乎適用於前兩個例子的事實是一隻紅鯡魚,它使我走錯了路。我仍然不能完全解釋 - 可能這只是運氣?我不確定。

請參閱這裏以獲取最有用的指針和PROGMEM資源:http://www.nongnu.org/avr-libc/user-manual/pgmspace.html