使用列表语法强制运行时阵列分配和初始化

时间:2013-11-01 22:51:14

标签: c arrays memory memory-management atmega

我正在开发 atmega328 只有2K的内存

我使用脚本从10个位图创建10bytes数组,代表我的LCD计时器的10位数字。那些字节数组存储在我的源代码中,但是因为我只写一个数字,所以没有理由将它们全部保存在RAM中。这样我可以使用更大的数字并消耗更少的RAM! / p>

这就是我想要做的事情:

void load_digit_ba(uint8_t digit, uint8_t digit_ba[]) {

  // from 0 to 9 I copy the current digit in the byte array form into digit_ba
  if (digit == 0) {
    uint8_t digit_ba_tmp[10] = { 24, 40, 0, 0, 0, 224, 240, 248, 252, 254 };

    memcpy(digit_ba, digit_ba_tmp, 10);
  }
...

}

但似乎编译器静态地为所有阵列保留了内存。在我的情况下,122字节* 10位= ~1K,超过我的一半RAM。

Sketch uses 7,310 bytes (23%) of program storage space. Maximum is 30,720 bytes.
Global variables use 1,695 bytes (82%) of dynamic memory, leaving 353 bytes for local variables. Maximum is 2,048 bytes

如果我将一个单元格添加到数组[11]而不是[10]并只传递10个值作为初始值,它将在运行时分配内存(似乎)

void load_digit_ba(uint8_t digit, uint8_t digit_ba[]) {

  if (digit == 0) {
    uint8_t digit_ba_tmp[11] = { 24, 40, 0, 0, 0, 224, 240, 248, 252, 254 };

    memcpy(digit_ba, digit_ba_tmp, 10);
  }
...

}

Aurdino IDE说:

Sketch uses 11,396 bytes (37%) of program storage space. Maximum is 30,720 bytes.
Global variables use 597 bytes (29%) of dynamic memory, leaving 1,451 bytes for local variables. Maximum is 2,048 bytes.

如果我uint8_t digit_ba_tmp[]允许编译器计算长度,它会保留〜1K RAM。

为什么添加一个单元格会干净?在我看来不对。 这里的假设是,由于数字数组的长度对于每个数字是固定的,只需改变内容,并且我通过串行发送一个数字到显示器,只需将当前数字加载到ram中然后发送它。我没有在这里看到任何堆/堆内存碎片问题,对不对?笑脸-SAD

0 个答案:

没有答案
相关问题