c++ - 如何在 AVR 上制作 2D PROGMEM 阵列的 1D PROGMEM 阵列(存储在闪存中)(例如 : ATMega) or Arduino microcontrollers

标签 c++ arrays arduino avr progmem

我在 PROGMEM 中有几个二维数组。

我想将它们存储到另一个数组中,因此有一个二维 PROGMEM 数组的 PROGMEM 数组。

那我要把数据读出来

这是我的

void myFunc()
{
  const static byte DATA1[3][2] PROGMEM = 
  {
    -1, 6,
    -3, 6,
    -5, 5
  };
  const static byte DATA2[3][2] PROGMEM = 
  {
    1,  0,
    1,  0,
    1,  0
  };
  const static byte DATA3[6][2] PROGMEM = 
  {
    0,  1,
    1,  3,
    2,  4,
    3,  4,
    4,  3,
    5,  1
  };
  //PROGMEM array of 2d arrays in PROGMEM
  const static byte* const MY_DATA[] PROGMEM = {DATA1, DATA2, DATA3}; 
  
  //read out the data now:
  byte myData = pgm_read_byte(&((MY_DATA[arrayNum])[x][y]));

  //use the data here, etc, etc...
}

我的错误是:

error: cannot convert 'const byte (*)[2] {aka const 
unsigned char (*)[2]}' to 'const byte* const {aka const
unsigned char* const}' in initialization

我应该怎么做?一个多小时以来,我一直在四处阅读并试图弄清楚这一点。我不知道我做错了什么。

有用的引用页面:

  1. http://www.nongnu.org/avr-libc/user-manual/pgmspace.html
  2. http://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html#ga963f816fc88a5d8479c285ed4c630229
  3. https://www.arduino.cc/en/Reference/PROGMEM

相关:

更新:6 年后(现在是 2022 年 6 月),这仍然是非常令人困惑的东西!

以下是我写的几个相关答案,它们有助于进一步提高清晰度。使用 typedef 也会显着提高此处已接受答案的清晰度。

  1. [我的回答] Passing 1D arrays as function parameters in C (and C++)
  2. [我的回答] How to use multidimensional (ex: 2D) arrays, and pointers to them, as function parameters in C and C++

最佳答案

MY_DATA的元素类型为const byte* const,但DATA1等被转换为const byte( *)[2] 如错误消息所示,因此会发生类型不匹配。请注意,表达式中的数组会自动转换为指向其第一个元素的指针,但某些异常(exception)情况除外,例如一元运算符 &sizeof

使用正确的类型:指向 const byte (*)[2] 的指针数组,如下所示:

const static byte(* const MY_DATA[])[2] PROGMEM = {DATA1, DATA2, DATA3};

这是“静态变量 MY_DATA 作为指向常量字节数组 2 的常量指针数组”。

根据 cdecl , const char(* const MY_DATA[99])[2]; 可以解码为“MY_DATA as array 99 of const pointer to array 2 of const char”。通过一些修改,您可以获得正确类型的实现。

您可以按照与正常表达式求值相反的顺序解码没有 const 的类型声明。 (抱歉,目前我不擅长解码限定符)让我在这个方法中解码 byte(*MY_DATA[])[2]

正常表达式评估:

  1. 我的数据
  2. MY_DATA[] : MY_DATA
  3. 的一些元素
  4. *MY_DATA[] : 取消引用元素
  5. (*MY_DATA[])[2] :取消引用的某些元素

解码类型声明(尚未解码的内容用@表示):

  1. byte @ :类型为 byte
  2. 的东西
  3. byte @[2] :byte
  4. 的 2 元素数组
  5. byte (*@)[2] :指向 byte 的 2 元素数组的指针
  6. byte (*@[])[2] :指向 byte 的 2 元素数组的指针数组
  7. byte (*MY_DATA[])[2] :MY_DATA,它是指向 byte 的 2 元素数组的指针数组

关于c++ - 如何在 AVR 上制作 2D PROGMEM 阵列的 1D PROGMEM 阵列(存储在闪存中)(例如 : ATMega) or Arduino microcontrollers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37903758/

相关文章:

c++ - 计算对象实例的最简单方法

javascript - 在CPU上预计算顶点

javascript - 如何将json对象显示为html?

python - 定义引脚时出现 InvalidPinDefError

c++ - 使用 alloca 分配内存时转换无效

arduino - 端口在 Arduino IDE 中处于非事件状态

c++ std::thread 构造函数用法

c++ - 模板重载解决问题

c++ - 在 QLabel 中显示图像

javascript - 使用 Javascript 从 JSON 中过滤唯一对