c语言 - 在 PIC32 上,如何在内存中分配 INT16 的数组?



基本上,我有一堆2字节的整数按顺序写入32位闪存。如何以 int16 数组的形式访问它们?

我编写了数组,而不考虑单词边界。但是我可以添加填充,以便在必要时数组从单词边界开始。

这是我写入闪存

的代码(基本上它只是将每 4 个字节组合成一个单词,然后将该单词写入闪存):

   for(flash_page = 0; flash_page < protocol_pages; flash_page++){ //loop through all the pages
       for(flash_address = 0; flash_address < NUMBER_OF_INSTRUCTIONS_IN_PAGE; flash_address++){ //loop through all the words in the page
           for (byte_address = 0; byte_address < 4; byte_address++){ //loop through the byte in each word
               buffer_check();
               flash_word += buffer[buffer_index] << (8*(3-byte_address));
               buffer_index++;
               bytes_written++;
               if(bytes_written >= data_length)
                   break;
           }
           ///////Write word here
           NVMWriteWord((void*) &(proto_data_addr[flash_page][flash_address]), flash_word);
           flash_word = 0;
           if(bytes_written >= data_length)
                break;
       }
       if(bytes_written >= data_length)
            break;
   }

混合到这个字节块中的是端到端串起的 2 字节整数序列。一旦它们写入闪存,我如何将它们作为一个阵列访问?我是否必须填充数组,以便每个单词中有 2 个 int16?

谢谢!

好的,

我知道了!我创建了一些不同类型的 const 数组,并使用调试器在内存中查看了它们。原来...它们都像您期望的那样按顺序排列。无填充。

诀窍是:每个 BYTE 都有自己的地址,而不是每个字(32 位)。因此,在编写了一堆int16的闪存后,您可以使用指针正常访问它们。

我错误地认为 INT16 的数组[a] 等效于 *(array+a) ,但它知道数据大小,所以它实际上等同于 *(array+(a*VARIABLE_SIZE))

最新更新