Essential for Beginners! A Quick Guide to C Language Structures in Embedded Development: From Data Packing to Memory Alignment

Essential for Beginners! A Quick Guide to C Language Structures in Embedded Development: From Data Packing to Memory Alignment

In the vast realm of embedded development, the C language shines like a brilliant star, holding a crucial position. For beginners with no background in embedded systems, mastering the core syntax of C is undoubtedly the key to unlocking this technical door. Today, we will focus on the extremely important structure part of the C language and embark on a thorough quick tour!

Essential for Beginners! A Quick Guide to C Language Structures in Embedded Development: From Data Packing to Memory Alignment1. Structures: The “Storage Masters” of Data

In daily life, we use different containers to store various items: a wardrobe for clothes, a shoe cabinet for shoes, and a storage cabinet for miscellaneous small items. In the world of C language, a structure is like a powerful “super storage box” that can integrate different types of data into a cohesive whole.

  • For example, when developing an embedded program for a smart home security system, we need to handle various information about sensors, such as the temperature value from a temperature sensor (which is a floating-point data type), the sensor’s ID number (which can be represented as an integer), and the sensor’s operational status (such as normal operation or failure, represented by a character type or enumeration).

  • If we did not have structures, we would have to define different variables to store these data, which would be very inconvenient to manage. With structures, we can “pack” these related data into a whole, making data management in the program simple and efficient.

2. Defining Structures: Creating Custom Data Containers

To use a structure as a “storage box”, we first need to define its shape, which means clarifying what types of data it can hold. The general form for defining a structure is as follows:

struct StructureName {    DataType memberName1;    DataType memberName2;    // More members can be added as needed};
  • For a specific example, let’s define a structure that describes student information:

struct Student {    char name[50];  // Used to store the student's name, here using a character array, assuming the name is at most 49 characters plus 1 for the null terminator '\0'    int age;        // Student's age    float score;    // Student's score};

In this definition, struct Student is a new data type we created, which contains three members: name (character array type), age (integer), and score (floating-point).

This is like creating a “storage box” specifically for storing student information, where each member has its own “compartment” for placing specific types of data.

3. Creating and Initializing Structure Variables: Filling the “Storage Box” with Data

Once the structure type is defined, we can create variables of that type, just like producing specific “storage boxes” according to the designed style and filling them with data. There are various ways to create structure variables, such as:

struct Student student1;  // Create a structure variable named student1// Next, we can assign values to the members of the structure variable one by onestrcpy(student1.name, "Xiao Ming");  // Use strcpy function to copy the string into the name memberstudent1.age = 18;student1.score = 95.5;// We can also initialize the structure variable directly upon creation:struct Student student2 = {"Xiao Hong", 17, 92.0};  // Initialize a structure variable named student2

This method is more concise and intuitive, filling the “storage box” with data all at once.4. Accessing Structure Members: Retrieving and Storing Data from the “Storage Box”

When we need to retrieve or modify data within a structure variable, we must access its members. In C language, this is done using the member selection operator “.”. For example:

printf("Student 1's name: %s\n", student1.name);printf("Student 1's age: %d\n", student1.age);printf("Student 1's score: %.2f\n", student1.score);
  • If we want to modify a member’s value, it’s also simple; for example, to increase student1’s score by 5 points:

student1.score += 5.0;

Essential for Beginners! A Quick Guide to C Language Structures in Embedded Development: From Data Packing to Memory Alignment5. Structure Arrays: Managing Multiple “Storage Boxes”

In actual embedded projects, it is often necessary to handle multiple structure variables of the same type. For example, to manage the information of all students in a class, defining structure variables one by one is clearly impractical. This is where structure arrays come into play. A structure array is an array where each element is a structure variable. The way to define a structure array is as follows:

struct Student class[30];  // Define an array that can hold 30 Student structure variables, representing a class of students

We can initialize the structure array using a loop. Suppose we perform simple initialization of the class students’ information (this is just an example; in reality, data might be read from a file or obtained through other means):

for (int i = 0; i < 30; i++) {    sprintf(class[i].name, "Student%d", i + 1);    class[i].age = 16 + i % 3;  // Assume ages are randomly distributed between 16 - 18 years    class[i].score = 60 + rand() % 41;  // Scores are randomly generated between 60 - 100 points}
  • Accessing elements in the structure array is also done using the array index combined with the member selection operator. For example, to output the score of the 5th student in the class:

printf("The score of the 5th student: %.2f\n", class[4].score);

6. Structure Pointers: A Powerful Tool for Flexibly Operating the “Storage Box”

Pointers are a powerful tool in C language, and structure pointers are no exception. A structure pointer is a pointer that points to a structure variable. The way to define a structure pointer is as follows:

struct Student *pStudent;  // Define a pointer to a Student structure variable
  • We can make the pointer point to an existing structure variable, for example:

pStudent = &student1;  // Make pStudent point to the student1 structure variable
  • When accessing structure members using a structure pointer, we cannot use the “.” operator; instead, we must use the “->” operator. For example:
printf("Accessing Student 1's name through pointer: %s\n", pStudent->name);printf("Accessing Student 1's age through pointer: %d\n", pStudent->age);

In embedded development, structure pointers are very useful.

For example, when dealing with linked lists, each node is a structure, and structure pointers are used to connect each node, achieving dynamic data storage and efficient operations.

When passing function parameters, if we want to pass a structure variable, passing a structure pointer is more efficient than passing the entire structure variable, as passing a pointer only requires passing 4 bytes (for 32-bit systems) or 8 bytes (for 64-bit systems) of address, rather than the entire size of the structure, which can greatly reduce memory overhead.

These are some of the uses of structures. For more information, please follow our account for further updates on C language content.

Next issue: “Must Learn C Language for Embedded Systems? Quick Guide to Core Syntax for Beginners (Bit Manipulation Edition)”

Follow “Learning Embedded from Scratch” to get embedded-related materials.From 51 microcontrollers to STM32 and Raspberry Pi development projects, learn at your own pace!!!Essential for Beginners! A Quick Guide to C Language Structures in Embedded Development: From Data Packing to Memory Alignment

Leave a Comment