C語言中的結構體指標



如果使用關鍵字struct定義了一個派生資料型別,則可以宣告此型別的變數。因此,您還可以宣告一個指標變數來儲存其地址。指向結構體的指標因此是一個引用結構體變數的變數。

語法:定義和宣告結構體

以下是如何使用“struct”關鍵字定義新的派生資料型別:

struct type {
   type var1;
   type var2;
   type var3;
   ...
   ...
};

然後可以宣告此派生資料型別的變數,如下所示:

struct type var;

然後可以宣告一個指標變數並存儲var的地址。要將變數宣告為指標,必須以“*”為字首;要獲取變數的地址,我們使用“&”運算子。

struct type *ptr = &var;

訪問結構體的元素

要使用指標訪問結構體的元素,我們使用一個稱為間接運算子 (→) 的特殊運算子。

在這裡,我們定義了一個名為book的使用者定義的 struct 型別。我們聲明瞭一個book變數和一個指標。

struct book{
   char title[10];
   double price;
   int pages;
};
struct book b1 = {"Learn C", 675.50, 325},
struct book *strptr;

要儲存地址,請使用&運算子。

strptr = &b1;

使用間接運算子

在 C 程式設計中,我們對 struct 指標使用間接運算子 (“”)。它也稱為“struct 解引用運算子”。它有助於訪問 struct 指標引用的 struct 變數的元素。

要訪問 struct 中的單個元素,間接運算子的使用方法如下:

strptr -> title;
strptr -> price;
strptr -> pages;

struct 指標使用間接運算子或解引用運算子來獲取 struct 變數的 struct 元素的值。點運算子 (“.”) 用於根據 struct 變數獲取值。因此,

b1.title is the same as strpr -> title
b1.price is the same as strptr -> price
b1.pages is the same as strptr -> pages

示例:指向結構體的指標

以下程式顯示了指向結構體的指標的用法。在此示例中,“strptr”是指向變數“struct book b1”的指標。因此,“strrptr → title”返回標題,類似於“b1.title”的作用。

#include <stdio.h>
#include <string.h>

struct book{
   char title[10];
   double price;
   int pages;
};

int main(){
   
   struct book b1 = {"Learn C", 675.50, 325};
   struct book *strptr;
   strptr = &b1;
   
   printf("Title: %s\n", strptr -> title);
   printf("Price: %lf\n", strptr -> price);
   printf("No of Pages: %d\n", strptr -> pages);

   return 0;
}

輸出

Title: Learn C
Price: 675.500000
No of Pages: 325

注意事項

  • 點運算子 (.) 用於透過 struct 變數訪問 struct 元素。
  • 要透過其指標訪問元素,必須使用間接運算子 (→)。

示例

讓我們考慮另一個示例來了解指向結構體的指標是如何工作的。在這裡,我們將使用關鍵字struct定義一個名為person的新派生資料型別,然後我們將宣告其型別的變數和一個指標。

系統提示使用者輸入該人的姓名、年齡和體重。透過使用間接運算子訪問結構體元素,將值儲存在結構體元素中。

#include <stdio.h>
#include <string.h>

struct person{
   char *name;
   int age;
   float weight;
};

int main(){

   struct person *personPtr, person1;

   strcpy(person1.name, "Meena");
   person1.age = 40;
   person1.weight = 60;

   personPtr = &person1;

   printf("Displaying the Data: \n");
   printf("Name: %s\n", personPtr -> name);
   printf("Age: %d\n", personPtr -> age);
   printf("Weight: %f", personPtr -> weight);
   
   return 0;
}

輸出

執行此程式時,將產生以下輸出:

Displaying the Data: 
Name: Meena
Age: 40
weight: 60.000000

C 允許您宣告“struct 陣列”以及“指標陣列”。在這裡,struct 指標陣列中的每個元素都是對 struct 變數的引用。

struct 變數類似於基本型別的普通變數,因為您可以擁有 struct 陣列,可以將 struct 變數傳遞給函式,以及從函式返回 struct。

注意:在宣告時,需要在變數或指標名稱前加上“struct 型別”。但是,可以透過使用typedef關鍵字建立簡寫表示法來避免這種情況。

為什麼需要指向結構體的指標?

指向結構體的指標非常重要,因為您可以使用它們來建立複雜的動態資料結構,例如連結列表、樹、圖等。此類資料結構使用自引用 struct,其中我們定義一個 struct 型別,其中一個元素是指向同一型別的指標。

具有指向其自身型別元素的指標的自引用結構體的示例定義如下:

struct mystruct{
   int a;
   struct mystruct *b;
};

我們將在下一章學習自引用結構體。

廣告