C-结构中的结构
时间:2020-02-23 14:32:01 来源:igfitidea点击:
在本教程中,我们将学习使用C编程语言处理结构中的结构。
我们已经在结构教程中学习了如何创建和访问结构的成员。
现在,让我们在结构内部添加结构并学习如何使用它。
在下面的示例中,我们有一个"学生"结构。
在它里面,我们有另一个结构" address"来保存地址细节。
//student structure having address structure inside
struct student {
char name[255];
char id[20];
//address of the student
struct {
char line1[255];
char line2[255];
char city[255];
char state[100];
char country[255];
char pincode[20];
} address;
};
在上面的代码片段中,我们可以看到在" student"结构内部有一个" address"结构。
到目前为止,我们已经知道要访问结构变量的任何成员,我们都需要使用.运算符。
因此,如果我们想访问student结构的name成员,我们必须编写以下内容。
std.name
类似地,如果我们要访问位于"学生"结构内部的"地址"结构的"城市"成员,则必须编写以下内容。
std.address.city
在下面的代码中,我们将从用户那里获取学生的详细信息,然后打印输出。
#include <stdio.h>
int main(void) {
//student structure having address structure inside
struct student {
char name[255];
char id[20];
//address of the student
struct {
char line1[255];
char line2[255];
char city[255];
char state[100];
char country[255];
char pincode[20];
} address;
};
//create structure variable
struct student std;
//take student data
printf("Enter student detail:\n");
printf("Name: ");
gets(std.name);
printf("ID: ");
gets(std.id);
printf("Address Line1: ");
gets(std.address.line1);
printf("Address Line2: ");
gets(std.address.line2);
printf("City: ");
gets(std.address.city);
printf("State: ");
gets(std.address.state);
printf("Country: ");
gets(std.address.country);
printf("Pincode: ");
scanf("%s", std.address.pincode);
//display result
printf("Student Detail:\n");
printf("Name: %s\n", std.name);
printf("ID: %s\n", std.id);
printf("\nAddress of the student:\n");
printf("%s\n", std.address.line1);
printf("%s\n", std.address.line2);
printf("%s, %s %s\n", std.address.city, std.address.state, std.address.country);
printf("%s\n", std.address.pincode);
return 0;
}
输出:
Enter student detail: Name: ID: s01 Address Line1: House #123 Address Line2: Awesome Street, 1024th Main Road City: Bangalore State: KA Country: India Pincode: 560001 Student Detail: Name: ID: s01 Address of the student: House #123 Awesome Street, 1024th Main Road Bangalore, KA India 560001

