C语言教程
C语言控制语句
C语言函数
C语言数组
C语言指针
C语言字符串
C语言数学函数
C语言结构
C语言文件处理
C预处理器

C语言嵌套结构

C提供了将一个结构嵌套在另一个结构中的功能,从而创建复杂的数据类型。例如,我们可能需要在结构中存储实体员工的地址。属性地址也可以包含子部分,例如街道编号,城市,州和密码。因此,要存储员工的地址,我们需要将员工的地址存储到一个单独的结构中,并将该结构的地址嵌套到该结构的员工中。请考虑以下程序。
#include<stdio.h>
struct address 
{
    char city[20];
    int pin;
    char phone[14];
};
struct employee
{
    char name[20];
    struct address add;
};
void main ()
{
    struct employee emp;
    printf("Enter employee information?\n");
    scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
    printf("Printing the employee information....\n");
    printf("name: %s\nCity: %s\nPincode: %d\nPhone: %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
}
输出
Enter employee information?
Arun            
Delhi           
110001       
1234567890    
Printing the employee information....   
name: Arun      
City: Delhi  
Pincode: 110001
Phone: 1234567890
可以通过以下方式嵌套该结构。
通过单独的结构 通过嵌入式结构

1)单独的结构

在这里,我们创建了两个结构,但是从属结构应在主结构内部用作成员。请考虑以下示例。
struct Date
{
   int dd;
   int mm;
   int yyyy; 
};
struct Employee
{   
   int id;
   char name[20];
   struct Date doj;
}emp1;
如您所见,doj(加入日期)是Date类型的变量。在这里,doj用作Employee结构的成员。这样,我们就可以在许多结构中使用Date结构。

2)嵌入式结构

嵌入式结构使我们能够在结构内部声明结构。因此,它需要较少的代码行,但不能在多个数据结构中使用。请考虑以下示例。
struct Employee
{   
   int id;
   char name[20];
   struct Date
    {
      int dd;
      int mm;
      int yyyy; 
    }doj;
}emp1;

访问嵌套结构

我们可以通过Outer_Structure.Nested_Structure.member访问嵌套结构的成员,如下所示:
e1.doj.dd
e1.doj.mm
e1.doj.yyyy

C嵌套结构示例

我们来看一个简单的C语言嵌套结构示例。
#include <stdio.h>
#include <string.h>
struct Employee
{   
   int id;
   char name[20];
   struct Date
    {
      int dd;
      int mm;
      int yyyy; 
    }doj;
}e1;
int main( )
{
   //storing employee information
   e1.id=101;
   strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
   e1.doj.dd=10;
   e1.doj.mm=11;
   e1.doj.yyyy=2014;
   //printing first employee information
   printf( "employee id : %d\n", e1.id);
   printf( "employee name : %s\n", e1.name);
   printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
   return 0;
}
输出:
employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014

将结构传递给函数

就像其他变量一样,结构也可以传递给函数。我们可以将结构成员传递到函数中,也可以一次传递结构变量。考虑以下示例,将结构变量employee传递给函数display(),该函数用于显示雇员的详细信息。
#include<stdio.h>
struct address 
{
    char city[20];
    int pin;
    char phone[14];
};
struct employee
{
    char name[20];
    struct address add;
};
void display(struct employee);
void main ()
{
    struct employee emp;
    printf("Enter employee information?\n");
    scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
    display(emp);
}
void display(struct employee emp)
{
  printf("Printing the details....\n");
  printf("%s %s %d %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
}

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4