Declaring struct variables
What you'll learn: How to create actual instances of a custom data structure so you can store and use data in your programs.
From blueprint to building
In the previous lesson, we defined what a struct looks like. However, defining a struct is like drawing a blueprint for a house—it describes the layout, but nobody can live inside a drawing. To actually store data, you must "build" the house by declaring a variable of that struct type.
When you declare a struct variable, the computer sets aside a block of memory large enough to hold all the individual members (like integers or characters) defined in your blueprint.
How to declare them
To declare a variable, you use the keyword struct followed by the name you gave your blueprint (the tag), and then your variable name.
Think of it like declaring an integer. Instead of writing int myNumber;, you write struct Player player1;. Here, struct Player acts as the full "type" name.
#include <stdio.h>
// The blueprint (definition)
struct Player {
int health;
int score;
};
int main() {
// Declaring the variables (creating the actual objects)
struct Player player1;
struct Player player2;
// Now player1 and player2 exist in memory and
// can hold their own unique health and score values.
return 0;
}
Local vs. Global declaration
Just like standard variables, where you declare your struct variable matters. If you declare struct Player player1; inside the main() function, only main can see it. If you declare it outside of any function, it becomes a global variable, accessible to your entire program.
Usually, you will define the blueprint (the "struct definition") at the top of your file or in a header, then declare the variables inside the functions where you need to perform work. This keeps your data organized and ensures you aren't wasting memory by creating "houses" where they aren't needed.
Key takeaway
A struct definition is just a template; you must declare a struct variable to allocate memory and actually store data.