C语言中的结构体指针

如果已使用关键字 struct 定义了派生数据类型,则可以声明此类型的变量。因此,您还可以声明指针变量来存储其地址。因此,指向 struct 的指针是引用 struct 变量的变量。

语法:定义和声明结构

这就是您将使用“struct”关键字定义新的派生数据类型的方式

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

然后,您可以声明此派生数据类型的变量,如下所示

struct type var;

然后,您可以声明指针变量并存储 var 的地址。要将变量声明为指针,它必须以“*”为前缀;为了获取变量的地址,我们使用“&”运算符。

struct type *ptr = &var;

访问结构的元素

为了使用指针访问结构的元素,我们使用称为间接运算符 (→) 的特殊运算符。

在这里,我们定义一个名为 book 的用户定义结构类型。我们声明一个 book 变量和一个指针。

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

要存储地址,请使用 & 运算符。

strptr = &b1;

使用间接运算符

在 C 编程中,我们使用带有结构指针的间接运算符 (“”)。它也被称为“结构取消引用运算符”。它有助于访问指针引用的结构变量的元素。

要访问结构中的单个元素,间接运算符的使用如下

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 type”的前缀。但是,您可以通过使用 typedef 关键字创建速记表示法来避免它。

为什么我们需要指向结构的指针?

指向结构的指针非常重要,因为您可以使用它们来创建复杂的动态数据结构,例如链表、树、图形等。这种数据结构使用自引用结构,其中我们定义一个结构类型,其元素之一作为指向同一类型的指针。

具有指向其自身类型元素的指针的自引用结构的示例定义如下

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

猜你喜欢

转载自blog.csdn.net/mzgxinhua/article/details/140378699
今日推荐