C 语言结构体指针

2025年3月17日 | 阅读 7 分钟

在本节中,我们将讨论 C 语言中的结构体指针。在深入概念之前,让我们先了解一下结构体。结构体是使用 struct 关键字在相同名称下分组的不同数据类型的集合。它也称为用户定义数据类型,它使程序员能够将不同数据类型的记录存储在结构体中。此外,结构体内部的数据元素集合称为成员

例如,假设我们要创建包含姓名、年龄、ID、城市等的个人记录,并且这些记录无法分组到一维数组中。因此,我们使用结构体来存储多个数据项的集合。

Structure Pointer in C

定义结构体的语法

这里 structure_name 是使用 struct 关键字定义的结构体名称。在 structure_name 内部,它收集了不同的数据类型(int、char、float)元素,称为成员。最后,str 是结构体的变量。

演示结构体及其成员访问的程序

此程序创建了一个学生结构体,并使用结构体变量和点(.)运算符访问其成员。

struct.c

输出

Name of the student s1 is: John
Roll No. of the student s1 is: 1101
 state of the student s1 is: Los Angeles
Age of the student s1 is: 20
Name of the student s1 is:  Mark Douglas
Roll No. of the student s1 is: 111
 The state of the student s1 is: California
Age of the student s1 is: 18

程序解释:如上程序所示,我们创建了一个名为 student 的结构体,该结构体包含不同的成员,如 name(char)、roll_no(int)、state(char)、age(int)。student 结构体还定义了两个变量,如 s1s2,它们在 main() 函数中通过点运算符访问结构体成员。

结构体指针

结构体指针指向存储结构体的内存块的地址。就像一个指针可以告诉内存中任何数据类型(int、char、float)的另一个变量的地址一样。在这里,我们使用结构体指针,它通过将指针变量 ptr 指向结构体变量来告诉内存中结构体的地址。

声明结构体指针

结构体指针的声明与结构体变量的声明类似。因此,我们可以在 main() 函数内部和外部声明结构体指针和变量。要在 C 语言中声明指针变量,我们在变量名前使用星号(*)符号。

定义结构体指针后,我们需要初始化它,如下面的代码所示

结构体指针的初始化

我们也可以在声明指针时直接初始化结构体指针。

如我们所见,指针 ptr 指向结构体 structure_variable 的地址。

使用指针访问结构体成员

有两种方法可以使用结构体指针访问结构体的成员

  1. 使用(*)星号或间接运算符和点(.)运算符。
  2. 使用箭头(->)运算符或成员运算符。

使用结构体指针和点运算符访问结构体成员的程序

让我们看一个示例,创建一个 Subject 结构体,并使用指向 Subject 变量地址的结构体指针在 C 语言中访问其成员。

Pointer.c

输出

Subject Name:  Computer Science
 Subject Id: 1201
 Duration of the Subject: 6 Months
 Type of the Subject:  Multiple Choice Question

在上程序中,我们创建了 Subject 结构体,它包含不同的数据元素,如 sub_name(char)、sub_id(int)、sub_duration(char)和 sub_type(char)。其中,sub 是结构体变量,ptr 是指向 sub 变量地址的结构体指针变量,例如 ptr = &sub。这样,每个 *ptr 都访问 Subject 结构体成员的地址。

使用结构体指针和箭头(->)运算符访问结构体成员的程序

让我们看一个程序,使用指针和箭头(->)运算符在 C 语言中访问结构体成员。

Pointer2.c

输出

Enter the name of the Employee (emp1): John
 Enter the id of the Employee (emp1): 1099
 Enter the age of the Employee (emp1): 28
 Enter the gender of the Employee (emp1): Male
 Enter the city of the Employee (emp1): California

 Second Employee:  
 Enter the name of the Employee (emp2): Maria
 Enter the id of the Employee (emp2): 1109
 Enter the age of the Employee (emp2): 23
 Enter the gender of the Employee (emp2): Female
 Enter the city of the Employee (emp2): Los Angeles

 Display the Details of the Employee using Structure Pointer
 Details of the Employee (emp1) 
 Name: John
 Id: 1099
 Age: 28
 Gender: Male
 City: California

 Details of the Employee (emp2) Name: Maria
 Id: 1109
 Age: 23
 Gender: Female
 City: Los Angeles

在上程序中,我们创建了一个 Employee 结构体,其中包含两个结构体变量 emp1emp2,以及指针变量 *ptr1*ptr2。Employee 结构体具有 name、id、age、gender 和 city 作为成员。所有 Employee 结构体成员通过指针变量和箭头运算符逐个从用户那里获取其各自的值,这些运算符决定了它们在内存中的位置。