C-结构
时间:2020-02-23 14:32:01 来源:igfitidea点击:
在本教程中,我们将学习C编程语言的结构。
如果我们想在C中存储单个值,我们可以使用任何基本数据类型,例如int,float等。
而且,如果我们想在一个变量名下存储相同数据类型的值,那么我们需要一个数组。
但是我们不能存储使用简单变量或者数组在逻辑上相关的不同数据类型值。
为此,我们利用关键字" struct"表示的结构。
结构的语法
以下是结构的语法。
struct tagName {
dataType member1;
dataType member2;
};
定义结构
我们使用struct关键字以C编程语言定义一个结构。
在下面的示例中,我们有一个"学生"结构,该结构由学生的名字,姓氏,ID和分数组成。
struct student {
char firstname[64];
char lastname[64];
char id[64];
int score;
};
注意点!
在上面的示例中,我们使用关键字" struct"定义了一个结构。
结构的名称是"学生",也称为结构标签。学生结构由四个数据字段组成,即名字,姓氏,ID和分数。
这些数据字段也称为结构元素或者成员。结构模板以分号结尾。
结构的成员不是变量,并且在创建结构变量之前它们本身不会占用任何内存空间。
创建结构变量
要创建结构变量,我们使用结构标签名称。
在下面的示例中,我们将创建类型为"学生"结构的结构变量" std1"。
//student structure template
struct student {
char firstname[64];
char lastname[64];
char id[64];
int score;
};
//creating student structure variable
struct student std1;
访问结构的成员
要访问结构的成员,我们使用结构变量名称和.成员运算符,后跟成员名称。
在以下示例中,我们将输出" std1"结构变量的" id"。
printf("ID: %s\n", std1.id);
用C编写程序以从用户那里获取学生详细信息,并将其存储在结构变量中,然后打印详细信息
在下面的示例中,我们将使用与本教程到目前为止讨论的相同的"学生"结构。
随时根据需要添加更多成员。
#include <stdio.h>
int main(void) {
//creating a student structure template
struct student {
char firstname[64];
char lastname[64];
char id[64];
int score;
};
//creating a student structure variable
struct student std1;
//taking user input
printf("Enter First Name: ");
scanf("%s", std1.firstname);
printf("Enter Last Name: ");
scanf("%s", std1.lastname);
printf("Enter ID: ");
scanf("%s", std1.id);
printf("Enter Score: ");
scanf("%d", &std1.score);
//output
printf("\nStudent Detail:\n");
printf("Firstname: %s\n", std1.firstname);
printf("Lastname: %s\n", std1.lastname);
printf("ID: %s\n", std1.id);
printf("Score: %d\n", std1.score);
return 0;
}
Enter First Name: Enter Last Name: Enter ID: student-01 Enter Score: 8 Student Detail: Firstname: Lastname: ID: student-01 Score: 8

