且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C中的自引用结构是什么?

更新时间:2023-02-02 23:25:04

代码如此

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.