Comprehensive Guide to C Language Structures

Click the blue text
Comprehensive Guide to C Language Structures
Follow us

Due to changes in public account push rules, please click “View” and mark as “Star” to get exciting technical shares in the first time

Source from the internet, infringement will be deleted

1. About C Language Structures:

First, why do we need to use structures? We have already learned many types like int, char, etc., and arrays composed of the same type elements, as well as pointers to the aforementioned types. In some small applications, these can be used flexibly. However, in our actual applications, declaring each variable separately and combining them seems impractical. For example, in managing a student’s information, they may have a name (char), student ID (int), and score (float), among other data. If we define these data separately, it will become particularly loose, complex, and difficult to manage. Therefore, we need to combine some related variables to describe an object as a whole, which is the benefit of structures.

2. First, we need to understand some small knowledge

2.1 **Only structure variables allocate addresses, while the definition of structures does not allocate space.**

2.2 The definitions of members in structures are the same as the previous variable definitions, but space is not allocated during the definition.

2.3 Structure variable declarations need to be declared above or within the main function; declaring them below the main function will cause an error.

2.4 In C language, structures cannot be directly forced to convert; only structure pointers can be forced to convert.

2.5 Members of the same type can be defined under the same type.

For example

struct Student

{

int number, age; // int type student ID and age

char name[20], sex; // char type name and gender

float score;

};

Don’t forget the final semicolon. Some compilers will add it automatically, so some students may overlook it.

3. About the definition and reference of structure variables

During compilation, the definition of a structure does not allocate storage space; only structure variables allocate corresponding storage space according to their data structure.

struct Book

{

char title[20]; // A string table

The title of the book

char author[20]; // A string representing the author

float value; // Price representation

};// This is just a declaration of the structure definition

struct Book book1, book2; // Definition of structure variables allocating space

book1.value; // Reference structure variable

After defining structure variables, the system will allocate memory units for them. For example, book1 and book2 occupy 44 bytes in memory (20+20+4). You can use the sizeof keyword in your compiler to find out the specific length.

For example

Comprehensive Guide to C Language Structures

Of course, it is important to note: When using the sizeof keyword to determine the length of a structure, the returned value is a multiple of the largest basic type’s byte size. For example, if we find the length to be 44, it is a multiple of float (4 bytes).

However, if we change title to title[22]; the normal length is 46, but you will find that the actual result is 48 (multiple of 4).

This involves the storage of structures:

1. The overall space of the structure occupies a multiple of the byte size of the largest member type.

2. The offset of each member relative to the structure’s starting address is a multiple of the byte size of the largest basic type member. If not, the compiler will automatically pad.

We will briefly introduce this:

1. Offset – The offset refers to the difference between the address of a member in the structure variable and the starting address of the structure variable, i.e., the offset in bytes. The size of the structure equals the offset of the last member plus its size. The offset of the first member is 0.

struct S1

{

char a;

int b;

double c;

};

Here, the offset of char a is 1. After that is int b. Since the offset 1 is not a multiple of int (4), it will be automatically padded. In double c, the offset is 8, which is a multiple of double (8), so no padding is needed. The final size of the structure is 16.

See the figure below:

Comprehensive Guide to C Language Structures

From the code above, students should have a simple understanding.

4. Initialization of Structure Variables

There are many points to note about the initialization of structures, here we will explain them.

First, here are several initialization methods.

Note: When initializing structure variables, each member of the structure must be assigned a value one by one. You cannot skip the preceding member variable and directly assign an initial value to the following member. However, you can assign values only to the first few, and for the subsequent unassigned variables, if they are numeric types, they will automatically be assigned 0; for character types, they will automatically be initialized to NULL, i.e., ‘\0’.

Comprehensive Guide to C Language Structures

4.1 Direct assignment during definition

struct Student

{

char name[20];

char sex;

int number;

} stu1 = {“zhaozixuan”, ‘M’, 12345};

// or

struct Student

{

char name[20];

char sex;

int number;

} ;

struct Student stu1 = {“zhaozixuan”, ‘M’, 12345};

Note that characters are in ‘ ’ while strings are in “”.

4.2 Assigning values one by one after defining

stu1.name = “王伟”;

stu1.sex = ‘M’;

stu1.number = 12305;

// You can also use strcpy function to assign values

strcpy(stu1.name, “王伟”);

4.3 Assigning values arbitrarily after definition

struct Student stu1 = {

.name = “Wang”,

.number = 12345,

.sex = ‘W’,

};// You can assign values to any variable

The benefit of this method is that you do not have to follow the order for initialization, and you can directly assign values to the variables you want to assign values to, while those you do not want to assign can be left unassigned.

It is important to note that if the structure variable is not initialized during definition, it cannot be initialized all together later.

Next, we will explain the initialization of structure arrays.

Here we will also mention typedef to explain the structure type.

Comprehensive Guide to C Language Structures

Here, BOOK is equivalent to an alias for struct book, making it very convenient to define structure variables.

This is mainly for level two exams, so we will briefly introduce it.

5. Reference of Structure Variables (Output and Input)

5.1 Assigning values to structure variables using scanf and outputting with printf is similar to operating other variables.

However, there are a few points to note:

(1) The dot (.) is the operator with the highest priority among all operators.

(2) If a member of a structure is itself a structure, you need to continue using the dot operator until the lowest-level member.

struct Student

{ char name[20];

char sex;

int number;

struct Date

{

int year;

int month;

int day;

} birthday;

} stu1;

printf(“%d”, stu1.birthday); // This is incorrect because birthday is also a structure variable

scanf(“%d”, &stu1.birthday.month); // Correct

(3) You can reference the address of structure variable members, and you can also reference the address of structure variables:

printf(“%o”, student); // (Output the address of student) (%o outputs in octal)

6. Structure Arrays and Their Initialization (Key Point)

Here we will briefly talk about structure arrays, which are composed of arrays of structure variables of the same type.

The difference between structure arrays and structure variables is just replacing structure variables with arrays.

struct Student

{

char name[20];

char sex;

int number;

} stu1[5] = {

{“zhaozixuan”, ‘M’, 12345},

{“houxiaohong”, ‘M’, 12306},

{“qxiaoxin”, ‘W’, 12546},

{“wangwei”, ‘M’, 14679},

{“yulongjiao”, ‘W’, 17857}

};

stu1[3].name[3] // Represents the fifth character of the name in the third structure variable of stu1

// If the initialization is already done in the structure array, you can omit the stu1[] during initialization.

Note that structure arrays must be initialized directly during definition; it is incorrect to define first and then assign initial values.

For example:

struct Student stu1;

stu1[3] = {

{“zhaozixuan”, ‘M’, 12345},

{“houxiaohong”, ‘M’, 12306},

{“qxiaoxin”, ‘W’, 12546}

};

This is incorrect.

Here, while writing, I encountered some issues, still regarding the initialization of structure arrays. After some effort, I solved it and would like to share it with everyone.

Regarding array initialization:

For example:

char str[20];

str = “I love you”; /* This will change the address of the array, but the address of the array is not allowed to change after being allocated */

In the first statement, str has already been defined as an array, and in the C99 standard, it is not allowed to assign a string (which is actually a pointer variable) to an array. Therefore, direct assignment is incorrect.

So what should we do?

Here are three methods:

1. Directly define during array definition

char str[20] = “I love you”;

2. Use strcpy or memset functions for copying

char str[20];

strcpy(str, “I love you”);

When using memset, some issues may arise.

Regarding the memset function, here is a brief introduction:

memset

void *memset(void *s, int c, size_t n)

Function: Set the first n bytes of the allocated memory space s to the value c.

char str[20];

memset(str, ‘a’, 20);

If it is a character type array, memset can be used freely. However, for other types of arrays, it is generally only used to clear to 0 or fill with -1. If filling with other data, it will cause errors.

int str[10];

memset(str, 1, sizeof(str)); // This is incorrect

Here we will discuss this error.

First, we need to know that memset assigns values byte by byte. Each time, the length of the data filled is one byte. For other types of variables, like int, which occupies 4 bytes, so sizeof(str) = 40; while using memset to assign values, it will fill the first 40 bytes pointed to by str with 0x01 (00000001). The operation of assigning 0x00000000 four times to 0x01 will result in 0x01010101 (00000001000000010000000100000001).

This is equivalent to assigning the operation of filling the first 10 ints with 0x01010101, resulting in a large error.

Comprehensive Guide to C Language Structures

Please be sure to pay attention to this. However, if clearing an array to zero, using memset is very convenient.

For simple usage, students can just use the strcmp function.

3. Using pointers (note memory allocation)

char *str;

str = “I love you”;

The essence of these two statements is to allocate a segment of memory in memory, place “I love you” in this segment of memory, and then hand over the address of this segment of memory to str. Since str is a variable, assigning it a value is legal.

Note that when initializing arrays, if the defined array is too long and we only initialize part of the data, for the uninitialized data, if they are numeric types, they will automatically be assigned 0; for character types, they will automatically be initialized to NULL, i.e., ‘\0’, filling the insufficient elements with default values.

As we mentioned in section 4.

For example:

int str[10] = {1}; // This only assigns the first element of str to 1, while the other elements default to 0.

Comprehensive Guide to C Language Structures

7. Structures and Pointers

We know that pointers point to the starting address of the memory occupied by the variable. In structures, pointers point to the starting address of the structure variable, and can also point to the elements of the structure variable.

Here we will divide it into three parts.

7.1 Pointers pointing to structure variables

The definition form is generally

struct structure name* pointer name;

For example: struct Student* p;

struct Student

{

char cName[20];

int number;

char csex;

} student1;

struct Student* p;

p = &student1;

// If it is a structure array

struct Student stu1[5];

struct Student* p;

p = stu1; // Because stu1 is a structure array, p = stu1 directly points to the starting address of stu1, so no need to add &.

Using structure pointer variables to access structure variable members can be done in the following two ways:

(*p).cName // The parentheses cannot be omitted, as mentioned in 5.1

p->cName

In simple terms, the following three forms are equivalent:

p->cName

(*p).cName

student1.cName

p->cName // Can perform normal operations

p->number++; // This increments the value in the structure variable number by one.

Here, it is important to note that comparisons will be made in 7.2.

7.2 Pointers pointing to structure arrays

In 7.1, we have already mentioned the naming of structure array pointers. Here we will introduce some knowledge points.

Next, we will talk about structure array pointers.

When we want to use pointers to access the nth data of a structure array, we can use

struct Student stu1[5];

struct Student* p;

p = stu[n];

(++p).number // Points to the address of the next element in the structure array

7.3 Structure members are pointer type variables

For example:

struct Student

{

char* Name; // This prevents waste of space due to varying lengths of names

int number;

char csex;

} student1;

When used, it can effectively prevent memory waste, but note that when referencing, be sure to allocate an address for the pointer variable. If you do not allocate an address, the result may be correct, but Name will be assigned to an arbitrary address, and the structure does not allocate any memory for strings, which has uncertainty, creating potential risks.

struct Student

{

char* Name;

int number;

char csex;

} stu, *stu;

stu.Name = (char*)malloc(sizeof(char)); // Memory initialization

Here we would like to mention that when students read books, they generally do not see this.

If we define a structure pointer variable and it does not point to a structure, then this structure pointer also needs to allocate memory initialization. The pointer type structure members corresponding to it also need to be initialized and allocated memory.

struct Student

{

char* Name;

int number;

char csex;

} stu, *stu;

stu = (struct Student*)malloc(sizeof(struct Student)); /* Structure pointer initialization */

stu->Name = (char*)malloc(sizeof(char)); /* Structure pointer member also needs to be initialized */

7.4 Binary tree traversal algorithm

The definition of the binary linked list type of binary trees is as follows:

typedef struct btnode {

datatype data;

struct btnode *lchild, *rchild;

} ;

Here we only mention the following because it involves linked lists. Students interested can go learn more (it will be needed for level two).

7.5 Structures as function parameters

First, one point we need to note is that when using structure variables as function parameters, a value passing method is adopted, which passes all the contents of the memory unit occupied by the structure to the formal parameter, and the formal parameter must also be the same type of structure variable. During use, a structure variable is automatically created as a copy of the original variable, which also needs to occupy memory. If the value of the member in the structure is modified during the function call (formal parameter), the modification is ineffective.

Comprehensive Guide to C Language Structures

However, if using a pointer as an actual parameter, the address of the structure is passed to the function. The address pointed to by the formal parameter is the address of the structure variable, and modifications can be made during this process, which is the essence of pointers.

Comprehensive Guide to C Language Structures

Here we will also provide several methods to swap two structures.

struct Student

{

char cName[20];

int number;

char csex;

} student1, student2;

struct Student student1 = {“Wang”, 12345, ‘W’};

struct Student student2 = {“Zhao”, 54321, ‘M’};

struct Student* stu1 = &student1;

struct Student* stu2 = &student2;

struct Student *student3;

student3 = stu1;

stu1 = stu2;

stu2 = student3; // Swap addresses

2. For structures of the same type, just swap the values.

struct stu student3;

student3 = student1;

student1 = student2;

student2 = student3;

// This can also be written using the strcmp function to swap.

3. Use the memcpy() function to swap.

4. A more cumbersome method: use a for loop to swap.

Finally, let’s mention memset to clear structures.

struct Student

{

char cName[20];

int number;

char csex;

} stu1;

In general, to clear str:

  str.cName[0] = ‘\0’;

  str.csex = ‘0’;

  str.number = 0;

  But we can use memset, which is very convenient:

  memset(&str, 0, sizeof(struct Student));

  If it is an array:

  struct Student stu[10];

  Then it is

  memset(stu, 0, sizeof(struct Student) * 10);


If you are over 18 years old and find learning 【C language】 too difficult? Want to try other programming languages? I recommend you learn Python. Currently, a 499 yuan Python zero-based course is available for free, limited to 10 places!



▲ Scan the QR code - Get it for free


Comprehensive Guide to C Language Structures
Click to read the original text to learn more

Leave a Comment