Structures
A struct
is just a container, packaging different related variables.
struct Rectangle { // (1)!
int width = 10; // (2)!
int length;
char* label;
} rect1; // (3)!
int main () {
struct Rectangle rect2; // (4)!
return 0;
}
- The name of the
struct
(Rectangle
in this case) is optional. struct
is just a blueprint for defining a type, therefore the variables inside (called themembers
) do not allocate storage unless a variable of typeRectangle
is declared. Thestruct
can be defined within a scope as well.- Defines a global variable
rect1
of typestruct Rectangle
. - Defines a local variable
rect2
of typestruct Rectangle
.
The struct
cannot contain itself but can contain pointer to it.
struct Node {
int value;
struct Node* leftNode;
struct Node* rightNode;
};
Padding and Size
You can also use sizeof
operator to find out the size taken up by a struct
.
struct Foo {
char x;
char y;
};
int main () {
printf("%d\n", sizeof(Foo)); // (1)!
}
- Outputs
2
.
struct Foo {
char x;
int y;
};
int main () {
printf("%d\n", sizeof(Foo)); // (1)!
}
- Outputs
8
. Because theint
takes4 bytes
, the compiler adds somepadding bytes
to thechar
to make it aligned.
Each green block represents a byte
for corresponding type
within the struct
.