C中的自引用结构是什么? [英] What is self-referencing structure in C?

查看:87
本文介绍了C中的自引用结构是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct LinkedList  
{  
    int data;
    struct LinkedList *next;
};

在代码中,在struct LinkedList的定义内,有一个指向结构本身的指针.

In the code, within the definition of struct LinkedList there is a pointer to the structure itself.

它如何工作?

推荐答案

代码如此

struct LinkedList  
{  
    int data;
    struct LinkedList *next;
};

定义一个包含两个分别名为datanext的成员的结构类型,其中next成员存储相同类型的 different 对象的地址.给出代码:

defines a struct type containing two members named data and next, with the next member storing the address of a different object of the same type. Given the code:

struct LinkedList Node1 = { .data = 1, .next = NULL };
struct LinkedList Node0 = { .data = 0, .next = &Node1 };

您得到的东西看起来像这样:

you get something that sort of looks like this:

Node0              Node1
+---+--------+    +---+------+
| 0 | &Node1 |--->| 1 | NULL |
+---+--------+    +---+------+

(请注意,您不会永远不会以这种方式创建链表,这只是为了说明).

(Note that you would never create a linked list this way, this is just for illustration).

这是有可能的,原因有两个:

This is possible for two reasons:

  1. C允许您声明指向不完整类型的指针;
  2. 指向struct类型的指针都具有相同的大小和表示形式.
  1. C allows you to declare pointers to incomplete types;
  2. Pointers to struct types all have the same size and representation.

这是一个自引用数据类型的示例,它仅表示该类型存储对相同类型的另一个对象的引用(指针).

This is an example of a self-referential data type, which simply means that the type stores a reference (pointer) to a different object of the same type.

这篇关于C中的自引用结构是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆