Tony Huy
Tony Huy

Reputation: 11

Referencing a struct within a struct

I have a C struct generated by an external tool. It looks like this:

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

Do the following leaves internalStruct pointed to some random value on the heap:

externalStruct_t* newExternalStruct = new externalStruct_t;

So here's my question:

How do I properly instantiate the pointer "internalStruct"?

Upvotes: 0

Views: 484

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

Here is how you can do it in C (C99 demo):

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

In C++ you would need to insert casts (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;

Upvotes: 1

Related Questions