I've been practicing Pat's questions recently, there are a lot of string data that needs to be stored using a two-dimensional string array, which is not very convenient to handle, and if the data to be stored is normalized for each row, consider using one-dimensional array of structures to process, and the following is a summary of the use of one-dimensional structure arrays:
Considering many topics the number of data in each test case is not certain, in other words, to use a variable-length one-dimensional structure array, the malloc function is used to dynamically request memory space:
1. First/define the structure body:
typedef struct {
Char id[20];
Char name[10];
Char gender[4];
} student;
2. Make a declaration in the main function:
int N;
scanf ("%d", &n);//Get array length
Student * Students = (student *) malloc (N * sizeof (student));
In compilers that support C99 standards, you can declare them directly by using the following methods:
Student Students[n];
3. About assigning values to an array of structures:
(1) directly using the For loop for the assignment of the struct body:
int i;
for (i = 0; i < N; i++)
{
If the structure is not a string, for example if the ID is an int, then the &students[i].id
scanf ("%s%s%s", Students[i].id,students[i].name,students[i].gender);
}
(2) by creating a new structure within the assignment function and returning the assignment:
In Main ():
int i;
Char id[20],name[10],gender[4];
for (i = 0; i < N; i++)
{
Students[i] = getstruct ();
}
struct Body Assignment function:
Student getstruct (void)
{
Student p;
scanf ("%s", p.id);//Because it is a string, you do not need to add an address character, otherwise this is &p.x
scanf ("%s", p.name);
scanf ("%s", P.gender);
return p;
}
(3) Assigning values through pointers:
In Main ():
int i;
Char id[20],name[10],gender[4];
for (i = 0; i < N; i++)
{
Getstruct (&students[i]);
}
struct Body Assignment function:
void Getstruct (Student * students)
{
scanf ("%s", students->id);//Because it is a string, it is not an int, this is &students->id
scanf ("%s", students->name);
scanf ("%s", Students->gender);
}