我有一个由外部工具生成的C结构。看起来像这样:
typedef struct externalStruct{
int msgID;
struct internalStruct {
long someValue;
} *internalStruct ;
} externalStruct_t;
请执行以下操作,让internalStruct指向堆上的某个随机值:
externalStruct_t* newExternalStruct = new externalStruct_t;
所以这是我的问题:
如何正确实例化指针“ internalStruct”?
最佳答案
这是使用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;