在c中初始化一个新结构

时间:2013-07-03 14:48:28

标签: c syntax struct

我试图在c。

中初始化一个新结构

我的语法有什么问题?

    AddressItem_Callback_ContextType *context;

   //check if icons need to be downloaded
   if (pEntity->cBigIcon[0] != 0){
      if (res_get(RES_BITMAP,RES_SKIN, pEntity->cBigIcon) == NULL){

          context = {pEntity->iID, pEntity->cBigIcon};
          //context->Icon = pEntity->cBigIcon;
          //context->iID = pEntity->iID;

         res_download(RES_DOWNLOAD_IMAGE, pEntity->cBigIcon, NULL, "",TRUE, 1, addressItem_icon_download_callback, context );
      }
   }

我也遇到了语法错误:

    AddressItem_Callback_ContextType *context = {0,NULL};

   //check if icons need to be downloaded
   if (pEntity->cBigIcon[0] != 0){
      if (res_get(RES_BITMAP,RES_SKIN, pEntity->cBigIcon) == NULL){

          //context = {pEntity->iID, pEntity->cBigIcon};
          context->Icon = pEntity->cBigIcon;
          context->iID = pEntity->iID;

         res_download(RES_DOWNLOAD_IMAGE, pEntity->cBigIcon, NULL, "",TRUE, 1, addressItem_icon_download_callback, context );
      }
   }

   if (pEntity->cSmallIcon[0] != 0){
      if (res_get(RES_BITMAP,RES_SKIN, pEntity->cSmallIcon) == NULL){

          //context = {pEntity->iID, pEntity->cSmallIcon};
          context->Icon = pEntity->cSmallIcon;
          context->iID = pEntity->iID;

         res_download(RES_DOWNLOAD_IMAGE, pEntity->cSmallIcon, NULL, "",TRUE, 1, addressItem_icon_download_callback, context );
      }
   }
那么这(3)应该有效吗?

 AddressItem_Callback_ContextType context = {0,NULL};

   //check if icons need to be downloaded
   if (pEntity->cBigIcon[0] != 0){
      if (res_get(RES_BITMAP,RES_SKIN, pEntity->cBigIcon) == NULL){

          //context = {pEntity->iID, pEntity->cBigIcon};
          context.Icon = pEntity->cBigIcon;
          context.iID = pEntity->iID;

         res_download(RES_DOWNLOAD_IMAGE, pEntity->cBigIcon, NULL, "",TRUE, 1, addressItem_icon_download_callback, context );
      }
   }

   if (pEntity->cSmallIcon[0] != 0){
      if (res_get(RES_BITMAP,RES_SKIN, pEntity->cSmallIcon) == NULL){

          //context = {pEntity->iID, pEntity->cSmallIcon};
          context.Icon = pEntity->cSmallIcon;
          context.iID = pEntity->iID;

         res_download(RES_DOWNLOAD_IMAGE, pEntity->cSmallIcon, NULL, "",TRUE, 1, addressItem_icon_download_callback, context );
      }
   }

2 个答案:

答案 0 :(得分:5)

context = {pEntity->iID, pEntity->cBigIcon};

{}初始化列表只能在声明时使用,不能在赋值表达式中使用。

你必须在两个赋值语句中将其分解(为此你还必须初始化未初始化的context指针)。

答案 1 :(得分:2)

正如ouah所说,初始化者必须在申报时使用,但在C99中你可以使用复合文字:

#include <stdio.h>

struct st {
    int a, b;
};

int main(void)
{
    struct st *t;

    t = &(struct st){1, 2};
    printf("%d %d\n", t->a, t->b);
    return 0;
}

在你的情况下

context = &(struct AddressItem_Callback_ContextType){pEntity->iID, pEntity->cBigIcon};