gpt4 book ai didi

c++ - 在 PROGMEM (Arduino) 中创建链表

转载 作者:行者123 更新时间:2023-11-30 04:11:22 26 4
gpt4 key购买 nike

我正在研究一个我认为基本上可以通过(乘法)链表很好解决的问题。然而,我的平台是一个 SRAM 非常有限的 Arduino,所以我想将它全部保存在 PROGMEM 中(使用 avr/pgmspace.h 库)。

我在引用我有指针的结构的字段时遇到问题。或者,换句话说,我在跟踪我的链接列表时遇到了问题。

下面是一些代码(我尽量缩短):

#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 函数来读取结构,但后来我不明白为什么它似乎对第一项有效。感谢您提供任何帮助或指向我应该阅读以理解这一点的内容。

最佳答案

好的,解决了。在 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

关于c++ - 在 PROGMEM (Arduino) 中创建链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20257394/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com