C Structures
Category Programming Techniques
1. Overview
The C language allows users to define a data structure that combines different types of data into a single entity for reference. These combined data within the entity are interrelated. Such a data structure is called a structure, which is equivalent to a record in other high-level languages.
The general form of declaring a structure type is as follows:
struct StructureName
{member list;};
The structure name serves as a marker for the structure type, also known as the structure tag. Inside the braces are the various members of the structure, which together form a structure. Each member should be declared with a type, such as:
TypeName MemberName;
The member list can also be referred to as the field list, and the first member is also known as a field within the structure. The naming rules for member names are the same as for variable names.
struct student
{
int num;
char name[20];
char sex;
int age;
float score;
char addr[30];
};
2. Methods for Defining Structure Type Variables
The previous section only specified a structure type, which is equivalent to a model, but it does not contain specific data, and the system does not allocate actual memory cells for it. In order to use data of the structure type in a program, structure type variables should be defined and specific data should be stored in them. There are three methods to define structure type variables.
(1) Declare the structure type first, then define the variable name
As the structure type struct student has been defined above, it can be used to define variables. For example:
struct student { //Structure type name
...
...
...
}student1, student2; //Structure variable names
Defines student1 and student2 as variables of the struct student type.
After defining the structure variables, the system will allocate memory cells for them. For example, student1 and student2 each occupy 59 bytes in memory.
It should be noted that the difference between defining a variable as a standard type (basic data type) and as a structure type is that the latter not only requires specifying the variable as a structure type but also requires specifying a specific structure type (such as struct student type), because many specific structure types can be defined. When defining a variable as an integer, it is only necessary to specify it as an int type.
(2) Define the variable while declaring the type
For example:
struct student
{
int num;
char name[20];
char sex;
int age;
float score;
char addr[30];
}student1, student2;
It has the same function as the first method, that is, it defines two variables of the struct student type, student1 and student2. The general form of this form of definition is:
struct StructureName
{
member list
}variable list;
(3) Directly define the structure type variable
The general form is:
struct
{
member list
}variable list;
That is, the structure name does not appear.
A few points need to be clarified about the structure type:
a. Type and variable are different concepts and should not be confused. Only variables can be assigned values, stored, or operated on, not types. At compile time, no space is allocated for types, only for variables.
b. Members of the structure (i.e., fields) can be used individually, and their function and status are equivalent to ordinary variables.
c. A member can also be a structure variable. For example:
struct date // Declare a structure type { int month; int day; int year; } struct student { int num; char name[20]; char sex; int age; struct date birthday; char addr[30]; }student1, student2;
First, a struct date type is declared, representing a date, including three members: month, day, and year. Then, when declaring the struct student type, the member birthday is specified as a struct date type.
- d. Member names can be the same as variable names in the program, but they do not represent the same object.
3. Referencing Structure Variables
(1) A structure variable cannot be input and output as a whole.
Only the individual members of a structure variable can be input and output separately. The way to reference a member in a structure variable is:
StructureVariableName.MemberName
For example, student1.num represents the num member in the student1 variable, that is, the num item of student1, and you can assign float score; };
void main() { struct student stu_1; struct student *p; p = &stu_1; stu_1.num = 89101; strcpy(stu_1.name, "Li Lin"); stu_1.sex = 'M'; stu_1.score = 89.5; printf("NO. :%ld\nname: %s\nsex:%c\nscore:%f\n", stu_1.num, stu_1.name, stu_1.sex, stu_1.score); printf("NO. :%ld\nname: %s\nsex:%c\nscore:%f\n", (p).num, (p).name, (p).sex, (p).score); system("pause"); }
In the main function, a struct of type student
is declared, followed by the definition of a variable of the same type, stu_1
. A pointer variable p
is also defined, pointing to a struct of type student
. During the execution of the function, the starting address of the struct variable stu_1
is assigned to the pointer variable p
, making p
point to stu_1
. Then, values are assigned to each member of stu_1
. The second printf
function is also used to output the values of each member of stu_1
, but in the form of (*p).num
, where (*p)
represents the struct variable pointed to by p
, and (*p).num
is the member num
of the struct variable pointed to by p
. Note that the parentheses around *p
cannot be omitted because the member operator '.' has higher precedence than the '*' operator; *p.num
is equivalent to *(p.num)
.
The results of the execution are as follows:
NO. :89101
name: Li Lin
sex:M
score:89.500000
NO. :89101
name: Li Lin
sex:M
score:89.500000
It can be seen that the results of the two printf
outputs are the same.
In the C language, for convenience and clarity, (*p).num
can be replaced with p->num
, which represents the member num
of the struct variable pointed to by p
. Similarly, (*p).name
is equivalent to p->name
.
That is, the following three forms are equivalent:
a. Struct variable. Member name
b. (*p). Member name
c. p-> Member name
The last printf
function can be rewritten as:
printf("NO. :%ld\nname: %s\nsex:%c\nscore:%f\n", p->num, p->name, p->sex, p->score);
The ->
is called the pointer operator.
Analyzing the following operators:
p -> n gets the value of member n in the struct variable pointed to by p
p -> n++ gets the value of member n in the struct variable pointed to by p, and then increments it by 1
++p -> n increments the value of member n in the struct variable pointed to by p by 1 (first increment)
6.2 Pointers to Structures and Structure Arrays
We have previously introduced the use of pointers to arrays or array elements, and similarly, pointers can also be used to point to structure arrays and their elements.
The application of pointers to structure arrays.
Example
#include <stdio.h>
#inlcude <stdlib.h>
struct student
{
int num;
char name[20];
char sex;
int age;
};
struct student stu[3] = {{10101, "Li Lin", 'M', 18},
{10102, "Zhang Fun", 'M', 19},
{10103, "Wang Min", 'F', 20}};
int main()
{
struct student *p;
printf("No. name sex age\n");
for(p=stu; p<stu+3;p++)
printf("%5d %-20s %2c %4d\n", p->num, p->name, p->sex, p->age);
system("pause");
}
The results of the execution are as follows:
No. name sex age
10101 Li Lin M 18
10102 Zhang Fun M 19
10103 Wang Min F 20
**Note the following c.next = NULL; // c node's next member does not store the address of another node p = head; // make the p pointer point to the a node do { printf("%ld %5.1f\n", p->num, p->score); // output the data of the node pointed to by p p = p->next; // make p point to the next node }while(p != NULL); // after the c node is output, the value of p is NULL system("pause"); }
Running results:
99101 89.5 99103 90.0 99107 85.0
### 7.3 Functions required for handling dynamic linked lists
**(1) malloc function**
void *malloc(unsigned int size);
The function's role is to allocate a block of memory with a length of size in the dynamic memory area. The value of this function (i.e., the return value) is a pointer to the starting address of the allocated space (with a base type of void). If the function is not successfully executed (e.g., insufficient memory space), it returns a NULL pointer.
**(2) calloc function**
void *calloc(unsigned n, unsigned size);
Its function is to allocate n contiguous spaces, each of length size, in the dynamic memory area. The function returns a pointer to the starting address of the allocated space; if the allocation is unsuccessful, it returns NULL.
The calloc function can be used to open dynamic storage space for a one-dimensional array, where n is the number of array elements, and each element has a length of size.
**(3) free function**
void free(void *p);
Its function is to release the memory area pointed to by p, making this part of the memory area available for other variables to use. p is the value returned by the last call to calloc or malloc. The free function has no return value.
Please note: In previous versions of C, the malloc and calloc functions provided pointers to character data. The malloc and calloc functions provided by ANSI C are defined as void * type.
### 7.4 Establishing a dynamic linked list
The so-called establishment of a dynamic linked list refers to the process of building a key table from scratch during the execution of the program, that is, to open nodes one by one, input the data of each node, and establish the relationship of linking before and after.
# Example
include <stdio.h>
include <stdlib.h>
define NULL 0
define LEN sizeof(struct student)
struct student { long num; float score; struct student *next; };
struct student *create() { struct student *p1, *p2, *head; int num; float score; int n = 0;
head = NULL;
p1 = p2 = (struct student *)malloc(LEN);
printf("please input num and score.\n");
scanf("%d,%f", &p1->num, &p1->score);
while(p1->num != 0)
{
n ++;
if(n == 1)
head = p1;
else
p2->next = p1;
p2 = p1;
p1 = (struct student *)malloc(sizeof(struct student));
printf("please input num and score.\n");
scanf("%d,%f", &p1->num, &p1->score);
}
p2->next = NULL;
return head;
}
void printlist(struct student *head) { struct student *p; p = head; if(head != NULL) { do { printf("num=%d score=%f\n", p->num, p->score); p = p->next; }while(p != NULL); } }
void main() { struct student *head; head = create(); printlist(head); system("pause"); }
**The following are various operations on the linked list**
Print the linked list:
void printlist(struct student *head) { struct student *p; p = head;
if(head != NULL)
{
do
{
printf("num=%d score=%5.2f\n", p->num, p->score);
p = p->next;
} while (p != NULL);
}
/* while(p -> next != NULL)
{
printf("num=%d score=%f\n", p->num, p->score);
p = p->next;
}*/
}