C Structures


C language provides Structure data type to group together different data types.

A structure can even store pointers to other structures, so creating a linked data structure.



Initializing structures

We define an example structure type st:
struct st {
int number;
char *str;
};


Initializing the structure within its declaration;
struct st first = {3, "hello"}


same with designated initializers:
struct st first = {.str="hello", .number=3}



If structure was previously declared we can use Compound literals in C99:
struct st second;
second = (struct st){3, "hello"};


same with designated initializers:
struct st second;
second = {.number=3, .str="hello"};



or member by member:
struct st third;
third.number = 8;
third.str = "bye";




Assigning structures

You can assign one structure to another without problem if they are of same type:

struct st foo = {2, "hello"};
struct st bar;
bar = foo;


Assign one struct to another in C



Comparing two structures:

It is needed to compare each member of the structure pair. C does no provide language help for this.



Function returning a structure

function returning a struct in C

How do C compilers implement functions that return large structures



Structures and typedef

Using typedef we can avoid writing struct keyword constantly: Why should we typedef a struct so often in C?

typedef is a better alternative than #define for type declarations: Are typedef and #define the same in c?

on the other side:
Linus rant about typedefs
Linux kernel coding style


E.g:
typedef struct st {int number; char *str;} st_t;
st_t first, second, third;
first = (st_t){3, "hello"}


Same with:
typedef struct {int number; char *str;} st_t, *st_p;



If we have NESTED STRUCTURES:
struct st {int number; char *str; struct st *next;};
typedef struct st st_t;
...
st_t a, b;
a.next = &b;


or

typedef struct st st_t;
struct st {int number; char *str; st_t *next;};
...
st_t a, b;
a.next = &b;


or

typedef struct st {int number; char *str; struct st *next;} st_t;
...
st_t a, b;
a.next = &b;




C bit fields

C bit fields

When to use bit-fields in C?



Optimizing memory size of a structure

The Lost Art of C Structure Packing

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

Data Structure Alignment