C语言结构体

C语言中的结构体是一种用户定义的数据类型,可以保存不同类型的数据元素。

结构体的每个元素都称为成员。

它像C++中的模板和Java中的类一样工作。可以有不同类型的元素。

例如,结构体可广泛用于存储学生信息,员工信息,产品信息,图书信息等。

定义结构体

struct关键字用于定义结构体。下面我们来看看在C语言中定义结构体的语法。

struct structure_name   
{  
    data_type member1;  
    data_type member2;  
    .  
    .  
    data_type memeberN;  
};

下面来看看如何在C语言中定义员工结构体的例子。

struct employee
{   int id;
    char name[50];
    float salary;
};

这里,struct是关键字,employee是结构体的标签名称; idnamesalary是结构体的成员或者字段。让我们通过下面给出的图来理解它:

声明结构体变量

我们可以为结构体声明变量,以便访问结构体的成员。声明结构体变量有两种方法:

  1. 通过main()函数中的struct关键字
  2. 通过在定义结构时声明变量。

第一种方式:

下面来看看一下struct struct来声明结构变量的例子。它应该在主函数中声明。

struct employee  
{   int id;  
    char name[50];  
    float salary;  
};

现在在main()函数中写入给定的代码,如下 -

struct employee e1, e2;

第二种方式:

下面来看看在定义结构体时声明变量的另一种方法。

struct employee  
{   int id;  
    char name[50];  
    float salary;  
}e1,e2;

哪种方法好?

但如果变量个数不固定,使用第一种方法。它为您提供了多次声明结构体变量的灵活性。

如果变量变量个数是固定的,使用第二种方法。它在main()函数代码中保存声明的变量。

访问结构成员

访问结构成员有两种方式:

  • 通过符号. (成员或点运算符)
  • 通过符号 ->(结构指针运算符)

下面下面来看看看代码访问p1变量的id成员的.操作符。

p1.id

结构体示例

我们来看看一个简单的C语言结构示例。创建一个工程:structure,并在此工程下创建一个源文件:structure-example.c,其代码如下所示 -

#include <stdio.h>  
#include <string.h>  
struct employee
{
    int id;
    char name[50];
}e1;  //declaring e1 variable for structure  

int main()
{
    //store first employee information  
    e1.id = 1010;
    strcpy(e1.name, "Max Su");//copying string into char array  
    //printing first employee information  
    printf("employee 1 id : %d\n", e1.id);
    printf("employee 1 name : %s\n", e1.name);
    return 0;
}

执行上面示例代码,得到以下结果 -

employee 1 id : 1010
employee 1 name : Max Su

下面我们来看看如何使用C语言结构体来存储多个员工信息的示例。

创建一个源文件:structure-more-employee.c,其代码如下所示 -

#include <stdio.h>  
#include <string.h>  
struct employee
{
    int id;
    char name[50];
    float salary;
}e1, e2;  //declaring e1 and e2 variables for structure  

int main()
{
    //store first employee information  
    e1.id = 1001;
    strcpy(e1.name, "Max Su");//copying string into char array  
    e1.salary = 18000;

    //store second employee information  
    e2.id = 1002;
    strcpy(e2.name, "Julian Lee");
    e2.salary = 15600;

    //printing first employee information  
    printf("employee 1 id : %d\n", e1.id);
    printf("employee 1 name : %s\n", e1.name);
    printf("employee 1 salary : %f\n", e1.salary);

    //printing second employee information  
    printf("employee 2 id : %d\n", e2.id);
    printf("employee 2 name : %s\n", e2.name);
    printf("employee 2 salary : %f\n", e2.salary);

    return 0;
}

执行上面示例代码,得到以下结果 -

employee 1 id : 1001
employee 1 name : Max Su
employee 1 salary : 18000.000000
employee 2 id : 1002
employee 2 name : Julian Lee
employee 2 salary : 15600.000000

上一篇: C语言strupr()函数 下一篇: C语言结构体数组