Structures containing structures and structures containing pointers

The next question is about C programming. I use the Microchip C30 compiler (because I know someone will ask)

What is the difference between a structure that contains several other structures and a structure that contains several pointers to other structures? Does someone do faster code execution than another? Does one method use more or less memory? Is memory shared at the same time in both cases?

If I use the following code, is memory allocated for subStruct automatically?

// Header file...

typedef struct{
    int a;
    subStruct * b;
} mainStruct;

typedef struct{
    int c;
    int d;
}subStruct;

extern mainStruct myMainStruct;

// source file...
mainStruct myMainStruct;

int main(void)
{
   //...
{
+3
source share
5 answers

, . , , malloc .

, :

  • struct 's
  • struct, , : ,
  • , +

, , :)

+2

, , .

- , , - .

poniters ( ).

+2

. :

myMainStruct.b=malloc(sizeof(*myMainStruct.b));

, , .

0

, . , , , , . , , , , .

// ( ), .

, - , " ". myMainStruct , b . malloc b subStruct myMainStruct.b .

0

, , ?

. " " , .

, ?

, . , .

?

number_of_pointers * sizeof(void*) . sizeof(void*) 4 32- 8 64-.

?

, malloc().

Pointers add an indirectness layer to the code , which is useful for switching substructures or having more than one pointer point on the same substructure. The presence of different master-structs pointing to common substructures, in particular, can save a lot of memory and distribution time.

0
source

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


All Articles