结构体应用及其字节对齐问题

在单片机中,结构体操作及其字节对齐问题(以LCD菜单为例)

 #include <stdio.h>
 
 typedef struct MenuItem {//28字节
 
   char cursorPosition;                //1 byte
   unsigned char menuItemTotal;        //1 byte
   bool isSelect;                      //1 byte
   //此处自动补充1个字节,字节对齐
   const unsigned char *icoSelected;   //4 byte
   const unsigned char *icoUnselected; //4 byte
   const char *title;                  //4 byte
   void (*Function)(void);             //4 byte
   struct MenuItem* parentMenu;        //4 byte
   struct MenuItem* childrenMenu;      //4 byte
 }MenuItem_typedef;
 
 
 const char* mainMenuLanguage[3][10] = {
   {"1.参数设置","2.密码修改","3.退出","4.退出","5.退出","6.退出","7.退出","8.退出","9.退出","10.退出",},
   {"1.param set","2.password modify","3.exit","4.exit","5.exit","6.exit","7.exit","8.exit","9.exit","10.exit",},
   {"1.參數設置","2.密碼修改","3.退出","4.exit","5.exit","6.exit","7.exit","8.exit","9.exit","10.exit",},
 };
 
 
 //变量声明
 MenuItem_typedef  menuL1_dev[10];
 MenuItem_typedef* pCurItem;
 const char * pCurTitle;
 
 int main(void)
 {
   for(int i=0; i<10; i++)
   {
     menuL1_dev[i].cursorPosition = NULL;
     menuL1_dev[i].menuItemTotal = 10;
     menuL1_dev[i].isSelect = false;
     menuL1_dev[i].icoSelected = NULL;//ico
     menuL1_dev[i].icoUnselected = NULL;
     menuL1_dev[i].title = mainMenuLanguage[0][i];
     menuL1_dev[i].Function = NULL;
     menuL1_dev[i].parentMenu = NULL;
     menuL1_dev[i].childrenMenu = NULL;
   }
 
   printf("%d \n", sizeof(const unsigned char *));//4字节
   printf("%d \n", sizeof(void (*)(void)));//函数指针4字节
   printf("%d \n", sizeof(bool));//1字节
   printf("%d \n", sizeof(struct MenuItem));//28字节
   printf("%d \n", sizeof(struct MenuItem *));//4字节
   printf("%d \n", sizeof(menuL1_dev));//280字节
 
   printf("menuL1_dev addr=%d \n", menuL1_dev);//addr1 = 4339288
   pCurItem = menuL1_dev + 1;
   printf("pCurItem addr=%d \n", pCurItem);//addr2= addr1+28 = 4339316
 
   pCurTitle = menuL1_dev->title + 2;
   printf("pCurTitle=%s \n", pCurTitle);//参数设置
 
   pCurTitle = (menuL1_dev+1)->title + 4;
   printf("pCurTitle=%s \n", pCurTitle);//码设置
 
   return 0;
 }
 

 

posted @ 2018-06-13 10:04  eruca520  阅读(298)  评论(0编辑  收藏  举报