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語言結構體數組