C语言 从类型“char *”分配给类型“char[128]”时的类型不兼容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17463487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:51:33  来源:igfitidea点击:

incompatible types when assigning to type 'char[128]' from type 'char *'

csyntaxstruct

提问by Elad Benda

I'm trying to assign char* field to char* field, but get this error:

我正在尝试将 char* 字段分配给 char* 字段,但出现此错误:

incompatible types when assigning to type 'char[128]' from type 'char *'

incompatible types when assigning to type 'char[128]' from type 'char *'

how can I fix this? and why is that happening?

我怎样才能解决这个问题?为什么会这样?

    AddressItem_Callback_ContextType *context = (AddressItem_Callback_ContextType *)malloc(sizeof(AddressItem_Callback_ContextType));

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

          context->Icon = pEntity->cBigIcon;
          context->iID = pEntity->iID;

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

declarations:

声明:

typedef struct
{
    int  iID;        //  POI Type ID
    int  iExternalPoiServiceID; // Service ID
    int  iExternalPoiProviderID; // Provider ID
    char cBigIcon[MAX_ICON_LENGHT];
    char cSmallIcon[MAX_ICON_LENGHT];
    char cBigPromotionIcon[MAX_ICON_LENGHT];
    char cSmallPromotionIcon[MAX_ICON_LENGHT];
    char cOnClickUrl[MAX_URL_LENGTH];
..
} RTExternalPoiType;

typedef struct
{
    int  iID;        //  POI Type ID
   //int  iExternalPoiServiceID; // Service ID
   // int  iExternalPoiProviderID; // Provider ID
    char Icon[MAX_ICON_LENGHT];
} AddressItem_Callback_ContextType;

采纳答案by Amit Bhaira

Array names are constant pointers you can not modify them. In this scenario Icon is a constant pointer and

数组名称是常量指针,您无法修改它们。在这种情况下 Icon 是一个常量指针和

            context->Icon = pEntity->cBigIcon;

here you are trying to modify it, which is not allowed.

在这里你试图修改它,这是不允许的。

Try this ..

尝试这个 ..

strcpy(context->Icon,pEntity->cBigIcon);

strcpy(context->Icon,pEntity->cBigIcon);

回答by

You can't assign to arrays (as the error message states). Copythe strings instead:

您不能分配给数组(如错误消息所述)。改为复制字符串:

snprintf(aStruct->member, sizeof(aStruct->member), "%s", someString);

Or, if you want to shoot yourself in the foot (prone to buffer overruns):

或者,如果您想用脚射击自己(容易发生缓冲溢出):

strcpy(aStruct->member, "the string");

Or, if you want to shoot yourself in the foot and not notice it (safe of buffer overruns, but doesn't NUL-terminate the string if too long):

或者,如果您想用脚射击而没有注意到它(缓冲区溢出是安全的,但如果太长,则不会以 NUL 终止字符串):

strncpy(aStruct->member, "the string", sizeof(aStruct->member));