Summary of C language structure knowledge

Article directory

1. What is a [structure]

In order to better simulate reality, it is necessary to combine various basic data types to form a new composite data type, and we call this custom data type a structure. Structure is a new composite data type formed by programmers combining various basic data types according to actual needs .

Second, the definition of the structure

There are three ways to define a structure, and only the most common and commonly used one is used here, namely:

struct structure name
{
    member list;
}; // Note that the semicolon cannot be omitted here

for example:

struct Student
{
    int age;
    float score;
    char gender;
};

Third, the definition of structure variables

The structure is the same as the basic data type we often use, it is also a data type, so we can use this data type to define its corresponding variables, we call the variables defined by the structure type as structure variables . The way to define a structure variable is as follows:

#include <stdio.h>

struct  Student // define the structure
{
    int age;
    float score;
    char gender;
};

int  main ()
 {
     struct  Student  stu ;  // define struct variables

    return 0;
}

Fourth, the initialization of structure variables

#include <stdio.h>

struct  Student // define the structure
{
    int age;
    float score;
    char gender;
};

int  main ()
 {
     struct  Student  stu = {  15 , 66.5 , 'M' }; // initialize struct variables

    return 0;
}

Five, the assignment of structure variables

#include <stdio.h>

struct  Student // define the structure
{
    int age;
    float score;
    char gender;
};

int  main ()
 {
     struct  Student  stu ;  // define struct variables

    stu.age = 15 ;       // Assign the age member in the structure variable 
    stu.score = 66.5 ;   // Assign the score member in the structure variable 
    stu.gender = 'M' ;   // Assign the value in the structure variable gender member assignment

    return 0;
}

Six, refer to the members of the structure variable

#include <stdio.h>

struct  Student // define the structure
{
    int age;
    float score;
    char gender;
};

int  main ()
 {
     struct  Student  stu ;   // define struct variables

    // Assign 
    stu.age = 15 to each member ;
    this.score = 66.5 ;
    stu.gender = 'M';

    printf ( "%d %f %c\n" , stu.age, stu.score, stu.gender); // output the content of each member

    return 0;
}

#include <stdio.h>

struct  Student // define the structure
{
    int age;
    float score;
    char gender;
};

int  main ()
 {
     struct  Student  stu ;   // define structure variable 
    struct  Student * pStu = & stu ;  // define structure pointer variable

    // Assign 
    pStu->age = 15 to each member ;
    pStu->score = 66.5 ;
    pStu->gender = 'M';

    printf ( "%d %f %c\n" , stu.age, stu.score, stu.gender); // output the content of each member

    return 0;
}

#include <stdio.h>

struct  Student // define the structure
{
    int age;
    float score;
    char gender;
};

int  main ()
 {
     struct  Student  stu ;  //define the structure variable 
    struct  Student * pStu = & stu ;  //define the structure pointer variable

    // Assign values ​​to each member 
    (*pStu).age = 15 ;
    (*pStu).score = 66.5 ;
    (*pStu).gender = 'M' ;

    printf ( "%d %f %c\n" , stu.age, stu.score, stu.gender); // output the content of each member

    return 0;
}

7. The problem of parameter passing of structure variables

When we define a structure variable in a function and want to operate the structure variable in another function, we need to pass parameters to the called function, then pass the structure variable as a parameter or should we pass the structure What about body pointer variables as parameters? This is a question that must be clarified. I take the following program as an example to illustrate the parameter transfer problem in different situations:

#include <stdio.h>
#include <string.h>

struct  Student // define the structure
{
    int age;
    float score;
    char name[100];
};

void input_student(struct Student* pStu);
void output_student(struct Student* pStu);

int  main ()
 {
     struct  Student  stu ;  // define struct variables

    input_student(&stu);     // For the reason for passing the address, see below the program 
    output_student(&stu);    // For the reason for passing the address, see below the program

    return 0;
}

// Assignment function 
void  input_student (struct Student * pStu)
 {
    (*pStu).age = 10 ;
    pStu->score = 66.5;
    /* 
        Note that it cannot be written as pStu->name = "Nansen";
        This is because the one-dimensional array name is a pointer constant, and the constant cannot be assigned an assignment.
    */
}

// output function 
void  output_student (struct Student* pStu)
 {
     printf ( "%d %f %s\n" , (*pStu).age, pStu->score, pStu->name);
}

  • [x] Why pass the address?
    Since the input_studentfunction needs to modify the value of each member of the structure variable in the main function stu, it can only transfer the address, not the variable stu. I have described the reasons in detail in the article [“Summary of Pointer Knowledge in C Language” .] The output_studentfunction does not need to modify the value of each member of the structure variable in the main function stu, so the variable can be transferred at this time stu, but because stuthe type of the variable is the structure type, it occupies a large number of bytes, and all the pointer variables There are only four bytes, so in order to reduce memory consumption and improve the efficiency of data transmission, the corresponding structure pointer variables are often transmitted.

8. Problems caused by the transmission address

Passing the address of a variable to a function can not only modify the value of the variable, but also improve the efficiency of data transmission, but doing so also has certain risks. For example, in the program in the previous summary, the output_studentfunction as an output function does not need to modify the value of the variable inside it, but once the address of the variable is passed in, it means that the output_studentfunction can also modify the variable corresponding to the address. This makes output_studentthis function very unsafe, so how can we achieve fast data transfer and prohibit the function from modifying data in functions that do not need to modify variable values? The answer is very simple, you only need to add the keyword before the pointer variable of the formal parameter constto achieve this purpose. As follows:

void output_student(const struct Student* pStu)
{
    pStu->score = 88 ; // Error, because the pointer variable pStu has const modification, the value of its corresponding ordinary variable cannot be modified 
    (*pStu).age = 10 ; // Error, because the pointer variable pStu has const modification , the value of its corresponding ordinary variable cannot be modified 
    printf ( "%d %f %s\n" , (*pStu).age, pStu->score, pStu->name);
}

Nine, dynamic structure array

#include <stdio.h>
#include <malloc.h>

// Define the structure 
struct  Student 
{ 
    char name[ 100 ];
     int age;
     float score;
};

int create_array(struct Student**);
void input_array(struct Student*, int);
void bubble_sort(struct Student*, int);
void print(struct Student*, int);

int main()
{
    int length;
    struct Student* pStu;

    length = create_array(&pStu); // Since the content of the pointer variable pStu needs to be modified, only its address can be transmitted
    input_array(pStu, length);
    bubble_sort(pStu, length);
    print(pStu, length);

    return 0;
}

// The function of this function is to allocate memory and construct an array 
int  create_array (struct Student** q)  // Since it needs to receive a first-level pointer variable, a second-level pointer is required here
 {
     int length;

    printf ( "Please enter the number of students:" );
     scanf ( "%d" , &length);
     printf ( "\n" );

    *q = (struct Student*) malloc ( sizeof (struct Student) * length); // Dynamically allocate memory to construct an array of structures

    return length;
}

// The function of this function is to assign each element in the structure array 
void  input_array (struct Student* p, int length)
 {
     int i;

    for (i = 0; i < length; i++)
    {
        printf ( "Please enter the information of the %d student:\n" , i + 1 );
         printf ( "Name:" );
         scanf ( "%s" , (p + i)->name);
         printf ( " age: " );
         scanf ( "%d" , &(*(p + i)).age);
         printf ( "Grade: " );
         scanf ( "%f" , &p[i].score);

        printf("\n");
    }
}

// The function of this function is to bubble sort according to the score members in the structure array from low to high 
void  bubble_sort (struct Student* p, int length)
 {
     int i, j;
     struct  Student  t ;

    for (i = 1; i < length; i++)
        for (j = 0; j < length - i; j++)
            if (p[j].score > p[j + 1].score)
            {   
                // Note: The size of the score is compared, but the position of the elements in the structure array needs to be swapped, not just the member score
                t = p[j];
                p[j] = p[j + 1];
                p[j + 1] = t;
            }
}

// The function of this function is to output the content of each element in the structure array 
void  print (struct Student* p, int length)
 {
     int i;

    printf ( "The result sorted from low to high is:\n" );

    for (i = 0; i < length; i++)
    {
        printf ( "Name: %s\n" , (p + i)->name);
         printf ( "Age: %d\n" , (*(p + i)).age);
         printf ( "Grade: % f\n" , p[i].score);

        printf("\n");
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *