R – When is it worth using a pointer to struct in a struct definition


Sorry if the question isn't clear; I found it pretty hard to explain in one sentence.

Say I have a struct with a member which is a struct, e.g. the following:

struct A {
    struct B b;

Lets say I intend instances of this structure to be heap-allocated always. Is there anything to be gained by changing it to this? (i.e. keeping a pointer to struct B)

struct A {
    struct B *b;

In the latter case I'd have a couple of functions such as make_A and free_A which would take care of allocating and de-allocating the memory pointed to by b;

The only example I can think of where the second form might be preferable is when not all instances of struct A will actually make use of b. In that case, memory could be saved by only allocating the extra memory for those instances which require it.

Are there any other cases where the second form offers something useful?

Best Solution

If every A will have exactly one B, you should not use a pointer to B.

Besides the fact that you don't need to bother with the extra memory management, it's actually slower and less efficient to allocate B.

Even if you want to pass a pointer to B to other code, you can still pass that address.