What is the method to define a structure in the C language?

In the C language, the struct keyword can be used to define a structure. The general syntax for defining a structure is as follows:

struct 结构体名 {
   数据类型1 成员变量1;
   数据类型2 成员变量2;
   // ...
   数据类型n 成员变量n;
};

The struct name is the name of the struct, which can be customized as needed. Member variable 1, member variable 2, member variable n are the struct’s member variables, and multiple member variables can be defined as needed, each with its own data type.

For example, below is an example defining a student structure.

struct Student {
   int id;
   char name[20];
   int age;
   float score;
};

After defining a struct, you can use it to declare struct variables. For example:

struct Student stu1;
struct Student stu2;

This defines two student structure variables stu1 and stu2, and the member variables of the structure variables can be accessed using the . operator, such as stu1.id, stu1.name, etc., for assignment or retrieval operations.

Furthermore, C language also supports using typedef to give an alias to structure types, making it easier to use. For example:

typedef struct Student {
   int id;
   char name[20];
   int age;
   float score;
} Student;

This allows you to declare a struct variable using just “Student” instead of adding the struct keyword, like “Student stu1;”.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds