Scan to follow Chip Dynamics and say goodbye to “chip” congestion!

Search WeChat
Chip Dynamics
Today we are going to talk about a super practical “data management tool”—the structure (Struct)!
Perhaps you have experienced this frustration while coding, with variables scattered everywhere: int age; char name[20]; float score; it feels like rummaging through a drawer for socks, worried about mismatching pairs, and pulling your hair out when you can’t find them?
Well, structures are here to help you “pair up”—pack related data into an “information envelope”, name it, type it, and organize it, so that data management is neat and orderly!
What is a structure?1.1 “Structure” in Daily Life
Imagine you want to send a package, and the shipping label needs to include: recipient’s name (string), phone number (number), address (string), weight (float). These pieces of information are originally scattered, but the shipping label packages them in a fixed format, making it easy for the courier to understand.
The C language structure does exactly this! It is a custom data type that can bind different types of data (like char, int, float) together, forming a “logical whole”.
1.2 Official Definition of Structure
A structure is a “template” for data, and the definition of a structure looks like this:
// Define a structure template for "Student"struct Student { char name[20]; // Name (up to 20 characters) int age; // Age float score; // Score};
Here, struct Student is the name of the structure type, equivalent to a “mold”. With this mold, we can mass-produce “student variables” (just like using a mold to make mooncakes).
Three Ways to Define Structure Variables
Now that we know the structure template, how do we use it to create variables? Don’t worry, there are three methods for you to choose from, and we will teach you all of them!
2.1 Method 1: Define the Template First, Then “Produce by Mold”
This is the clearest and most commonly used method: first write the structure template, then declare the variables:
// Step 1: Define the structure template (mold)struct Student { char name[20]; int age; float score;}; // Step 2: Use the template to produce variables (e.g., Zhang San, Li Si)struct Student stu1; // Zhang San's envelopestruct Student stu2; // Li Si's envelope
Advantages: The template and variables are separated, making it clear.
Note: struct Student is a whole type name, so don’t forget the struct keyword when writing (it must be included in C, but can be omitted in C++).
2.2 Method 2: “Direct Production” When Defining the Template
If there are not many variables and it suits a simple scenario, you can declare variables while defining the template to avoid writing it twice:
struct Student { char name[20]; int age; float score;} stu1, stu2; // Directly create two student variables
Advantages: The code is concise, suitable for temporary variables.
Disadvantages: If you need to create more variables later, you have to write the template again (not as flexible as Method 1).
2.3 Method 3: “Anonymous Template” Directly Create Variables
There is an even more “geeky” way—create variables directly without defining a template name:
struct { // No template name! char name[20]; int age; float score;} stu1, stu2; // Can only create these two variables, cannot reuse the template
Advantages: The code is shorter, suitable for one-time use variables.
Disadvantages: The template cannot be reused (for example, if you want to create another variable next time, you cannot directly use this structure), and beginners may easily fall into pitfalls, so it is not recommended for daily use!
Some Notes on Structure Variables:
-
A structure and a structure variable are different concepts; you can only assign values, access, or perform operations on variables, but not on a type. During compilation, no space is allocated for types, only for variables.
-
Members of a structure can be used individually, and their role and status are equivalent to ordinary variables.
-
Structure members can also be a structure variable.
struct date{ int month; int day; int year;};struct student{ char name[20]; int age; float score; struct date birthday; // birthday is of struct date type}; // Memory distribution diagram (assuming no memory alignment issues) +----------------------+-----------+-----------+| name[20] | age | score |+----------------------+-----------+-----------+| 0-19 bytes (20 bytes) | 20-23 bytes | 24-27 bytes | +----------------------+-----------+-----------++-------------------------------+| birthday (date) |+-------------------------------+| 28-39 bytes (month, day, year) |+-------------------------------+
Accessing Structure Variables
Now that we have created structure variables (like stu1), how do we read or modify the data inside?
-
You cannot input and output a structure as a whole.
struct Student { char name[20]; int age; float score;} stu1;printf("%s,%d,%f",stu1); // Error
-
You can only input and output each member of the structure separately. The way to access members of a structure variable is:
structure variable name.member name
stu1.age = 18;
-
If a member itself belongs to a structure type, you need to use several member operators to find the lowest level member step by step. You can only assign values or access and perform operations on the lowest level members.
stu1.birthday.year = 2025;
Initializing Structure Variables
Initialization means giving initial values to the members of a structure variable. Don’t think you can just fill them in randomly—filling in the wrong order or type can lead to errors!
4.1 Method 1: Sequential Initialization
Assign values in the order defined by the structure members, like filling out a form:
// Correct example: Sequential initialization (Name → Age → Score)struct Student stu1 = {"Zhang San", 18, 90.5}; // Incorrect example: Wrong order! (putting age in the name position will cause a compiler warning)struct Student stu2 = {18, "Zhang San", 90.5}; // Warning: Type mismatch
Note:
-
The order must be exactly the same as the order defined by the structure members;
-
The types must match (for example, if name is char[20], you cannot fill in int);
-
If a member is a char array, you must use a string literal (like “Zhang San”), not a single character (like ‘Zhang’).
4.2 Method 2: Designated Member Initialization
C99 introduced the “designated member initialization” feature, allowing you to assign values using .member name=value, regardless of order, and you can skip certain members (leave them empty):
// Designated member initialization (order doesn't matter, only fill in what you need)struct Student stu3 = {.age = 19, .name = "Li Si"}; // Score not filled, defaults to random value (dangerous!)// Safer way: Explicitly initialize all members (avoid random values)struct Student stu4 = {.name = "Wang Wu", .age = 20, .score = 88.5};
Advantages:
-
Member order is irrelevant, making the code more readable (for example, it’s clear who comes first between age and name);
-
Suitable when there are many structure members, only initializing some members (but uninitialized members will have random values).
Pitfall GuidePitfall 1: Structure Name and Variable Name Collision
For example, writing like this:
struct Student Student; // Structure name is Student, variable name is also Student (not recommended, but no error!)
Although the compiler does not report an error, the readability is very poor.
Pitfall 2: Uninitialized Structure Pointer
For example, if a function wants to modify the value of a structure variable but passes a pointer that is not initialized:
void set_age(struct Student* stu) { stu->age = 20; // Dangerous! If stu is NULL, this will crash!}int main() { struct Student* stu_ptr; // Uninitialized pointer (wild pointer) set_age(stu_ptr); // Crash! Accessing invalid memory return 0;}
Correct approach:
-
When passing parameters to functions, ensure the pointer points to valid memory (for example, first malloc to allocate space, or point to an already defined variable);
-
Initialize the pointer: struct Student* stu_ptr = &stu1; (pointing to an existing variable) or stu_ptr = (struct Student*)malloc(sizeof(struct Student)); (dynamic allocation).
Conclusion
Structures are not just “syntax games”; they are the “underlying logic” for organizing data in C language. Mastering them can elevate you from “writing code” to “designing data”, making it much easier to learn linked lists, hash tables, and file operations later on!
Next time you write code, try using structures to package scattered variables, and you will find—data management can be this refreshing!

If you find this article helpful, click “Like”, “Share”, “Recommend”!