Dynamic allocation of a structure within a structure

I dynamically highlight a structure that has a different structure as a member:

struct a { // other members struct b; } 

struct b basically contains a pointer to another struct b , so think of struct b as a linked list.

If I dynamically allocate struct a , then this will also make a new struct b . However, what is the difference between doing this or having struct a hold a pointer to struct b and dynamically allocating struct b inside struct a ? What is the difference in implementation?

+4
source share
3 answers

If you dynamically allocate (malloc) struct a , as in

 struct a *temp = (struct a *)malloc(sizeof(struct a)); 

you are malloc space for a pointer to struct b (assuming that is in struct a ), but you are not a malloc space for struct b . That means you have to do

 temp->b = (struct b *)malloc(sizeof(struct b)); 

before trying to use struct b .

If you do not store a pointer to struct b , but rather struct b , then you will get an automatic allocation when you define struct a .

+8
source

First, let's define real definitions to make this concrete.

 struct b { int x; }; struct a_with_b { struct bb; } struct a_with_b_ptr { struct b *bp; } 

When you encapsulate a structure, you just need to highlight the external structure (and since the internal structure is not a pointer, you use . To refer to members of the internal structure):

 struct a_with_b *a1 = malloc(sizeof(struct a_with_b)); a1->bx = 3; 

But when you encapsulate a pointer, you must select each independently and use -> when referring to members of the internal structure:

 struct a_with_b_ptr *a2 = malloc(sizeof(struct a_with_b_ptr)); a1->b = malloc(sizeof(struct b)); a1->b->x = 3; 
+9
source

The difference is really equivalent to any other situation when you are comparing “automatic” and “dynamic” distribution. 1

From a management point of view, when you should use a pointer element, I would say that you should avoid it if it has no good reason, due to the lack of a programmer when working with manual memory management (and errors that it inevitably leads to )

An example of a good reason would be if you need your structure a to reference an existing structure b .


<Sub> 1. "automatic" is the term used in the C standard for this kind of allocation, since the memory is cleared automatically.
+3
source

Source: https://habr.com/ru/post/1403365/


All Articles