引用结构中的结构

时间:2013-07-25 17:59:05

标签: c struct

我有一个外部工具生成的C结构。它看起来像这样:

typedef struct externalStruct{
    int  msgID;
    struct internalStruct {     
        long someValue;
    } *internalStruct ;
} externalStruct_t;

执行以下操作时,internalStruct指向堆上的一些随机值:

externalStruct_t* newExternalStruct = new externalStruct_t;

所以这是我的问题:

如何正确实例化指针“internalStruct”?

1 个答案:

答案 0 :(得分:1)

以下是如何在C(C99 demo)中执行此操作:

externalStruct_t* newExternalStruct = malloc(sizeof(externalStruct_t));
newExternalStruct->internalStruct = malloc(sizeof(*newExternalStruct->internalStruct));

在C ++中,您需要插入强制转换(C++ demo):

externalStruct_t* newExternalStruct = new externalStruct_t;
// You need to rename internalStruct to internalStructType
// to avoid a naming collision:
newExternalStruct->internalStruct = new externalStruct::internalStructType;