c - Difference between a struct and a pointer to a struct -


i trying understand difference between struct , struct pointer. following code example.

code example:

 #include<stdio.h>  typedef struct{      const char *description;      float value;  } swag;   typedef struct{      swag *swag;  } combination; 

as can see there 2 structs here swag, combination. struct combination has pointer struct swag. why can't this:

 typedef struct{      swag swag;  } combination; 

why have swag *swag. can please explain me difference between 2 code examples?

both possible, how appear in memory:

case 1

      +----+-----+----------+   +->|    p     |   value  |      struct swag   |  +----------+----------+   |  const char*    float   |   |  +----------+   +--+   swag   |                 struct combination      +----------+          swag* 

case 2

     +-----------------------+     |+----+-----+----------+|     ||    p     |   value  ||     struct combination     |+----------+----------+|     +-----------------------+ 

the advantage of case 1 swag* may pointing null when there's no data , can point allocated structure otherwise. while in case 2, have incur space complete swag structure.

however, case 2's advantage there no memory management issues specific allocating , deallocating space swag structure, since there. case 2 may better locality of reference since there's no pointer dereference , spoil cache coherence. total space lesser case 2 when both cases hold data; case 1: sizeof(swag) + sizeof(swag*); case 2: sizeof(swag).


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -