无法转换为指针类型,Casting structs

时间:2014-10-07 19:05:32

标签: c pointers

将结构转换为指针时,我收到“无法转换为指针类型”错误。

我试图将ObjectExtended类型的结构转换为ObjectBase的指针,ObjectExtended的第一个成员是指向ObjectBase的指针,因此它应该可以工作。

以下是代码:

typedef struct ObjectBase
{
    int integer1;
    int integer2;
}ObjectBase;

typedef struct ObjectExtended
{
    ObjectBase* baseObj;
    char* string;
}ObjectExtended;

int main(int argc,char** argv)
{
    ObjectExtended* objExtended = malloc(sizeof(ObjectExtended));
    objExtended->string = "TEST_OBJECT";

    objExtended->baseObj = malloc(sizeof(ObjectBase));
    objExtended->baseObj->integer1 = 10;
    objExtended->baseObj->integer2 = 11;

    printf("Extended Object:\n");
    printf("\tString: %s\n",objExtended->string);
    printf("\tInt1: %i\n",objExtended->baseObj->integer1);
    printf("\tInt2: %i\n",objExtended->baseObj->integer2);

    ObjectBase* objBase = (ObjectBase*)(*objExtended);
    printf("Base Object:\n");
    printf("\tInt1: %i\n",objBase->integer1);
    printf("\tInt2: %i\n",objBase->integer2);

    free(objExtended->baseObj);
    free(objExtended);
    return 0;
}

3 个答案:

答案 0 :(得分:0)

    ObjectBase* objBase = (ObjectBase*)(*objExtended);

应该是

    ObjectBase* objBase = (ObjectBase*)objExtended;

我想。您无需取消引用objExtended

答案 1 :(得分:0)

您似乎想要ObectBase的{​​{1}}“组件”。只需使用字段名称

ObjectExtended

这只是

的另一种拼写
ObjectBase* objBase = objExtended->baseObj;

对于类似对象的转换,它只是没有在C中定义,只有转换中允许标量类型,你不应该试图欺骗C的类型系统。

答案 2 :(得分:0)

将您的代码更改为

  ObjectBase* objBase = (ObjectBase *)objExtended; //Compiles and running, but gives wrong answer.

如果答案正确,可以写

 ObjectBase* objBase = (ObjectBase *)objExtended->baseObj;

 ObjectBase* objBase = objExtended->baseObj;