C中的自引用结构是什么? [英] What is self-referencing structure in 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;
};
定义一个包含两个分别名为data
和next
的成员的结构类型,其中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:
- C允许您声明指向不完整类型的指针;
- 指向
struct
类型的指针都具有相同的大小和表示形式.
- C allows you to declare pointers to incomplete types;
- 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屋!