A struct is a collection of different variables with varying types. They are allocated and accessed together. When we declare them, they don’t change in size/composition. As such struct definitions (their shape) are known at compile time, however they can be dynamically allocated on the heap.
Structs are aligned to the largest of their member’s alignments. So for example, if a struct contains
struct X {
char a;
char b;
int i
}It would be 4-byte aligned.
If it were this struct:
struct Y {
long a;
char b;
int c;
}It would be 8-byte aligned.
This expands to include other structs as well, so if a you have a struct inside a struct like as follows:
struct Z {
int a;
char b;
struct Y;
}The alignment requirement would be 8 bytes, since struct Y has an alignment requirement of eight bytes.
This means that in the above example of struct Y, the offset of c is 16 bytes, because the struct is padded to accommodate for the largest member ‘a’ in order to satisfy the 8 byte alignment.
Combined with Arrays
You can have arrays inside a struct like so:
struct S {
int i;
int j[10];
}You can also have arrays of structs like so
struct S a[42];Which would be an array of 42 struct S.
You can also have arrays of pointers to a struct like so:
struct S* b[42];Access
Accessing a member of a struct is done via the . operator. It can also be done via the -> operator if you have a pointer to the struct, in which case
struct S s*;
s->i;
//is the same as
(*s).i;
//BUT NOT THE SAME AS:
*s.i; //This is invalid because of operator precedence in C!Initialization
Struct can be initialized following a few different syntaxes:
struct X {
char a;
char b;
int i
}
struct X x = {4, 4, 2893};
//OR
struct X x;
x.a = 4;
x.b = 4;
x.i =2893;
//since C23, you can also empty-initialize structs, though most CS classes will not be up to date with this syntax so don't use it:
struct X x = {};They can also be initialized with designated initializer.