你能解释一下结构体内部的指针是什么意思吗?递归结构为什么有用?你能给我解释一下这个代码吗?它在记忆中的表现又是怎样的呢?下面是我的C代码:
struct State {
unsigned long Out;
unsigned long Time; //ms
const struct State *Next[4];};
在这种情况下,Next
可以在只读地址中保存4个指向同一类型对象(struct State
)的指针(4个不可修改的引用)。
一个例子:
#include <stdio.h>
#include <stdlib.h>
struct State {
unsigned long Out;
unsigned long Time; //ms
const struct State *Next[4];
};
void fn(struct State *data)
{
/* data->Next[0]->Out = 1; error: assignment of member ‘Out’ in read-only object */
for (int i = 0; i < 4; i++) {
printf("%ld %ldn", data->Next[i]->Out, data->Next[i]->Time);
free((struct State *)data->Next[i]); /* cast to non const */
}
}
int main(void)
{
struct State data;
struct State *next;
for (int i = 0; i < 4; i++) {
next = malloc(sizeof(*next));
next->Out = i;
next->Time = i * 10;
data.Next[i] = next;
}
fn(&data);
return 0;
}
可以参考链表的例子来理解自引用指针的用法。
const struct State *Next[4]; array of pointer.
所以它可以用来指针4自引用地址。
在下面的链接
中找到链表示例http://www.thegeekstuff.com/2012/08/c-linked-list-example/这不是一个"递归struct
"。包含指向State
的指针与拥有State
成员是不一样的。下面的代码将导致错误:
// error!!
struct State {
unsigned long IN;
State someState;
};
因为内部State
成员必须在其内部有另一个State
成员,依此类推,深入递归的兔子洞。
指针是有用的。考虑一个State
结构体链表的示例实现。从概念上讲,它看起来像这样:
----- ---> -----
| 9 | | | 5 |
----- | -----
| 5 | | | 4 |
----- | -----
| -|--- | -|----->
----- -----
第二个成员包含指向另一个结构体的指针。在c++中,通常有其他选择。例如,对于链表,您可以这样做:
#include <list>
struct State {
unsigned long IN,
unsigned long OUT,
};
std::list<State> my_list;
如果在结构体内部有指针,则该指针称为"Self - referential pointer "。该指针将指向自己的结构体。
struct State {
unsigned long Out;
unsigned long Time; //ms
const struct State *Next[4]; // array of 4 self referential pointer.
};
这些*Next[4]
将指向自己的结构体。包含自引用指针的结构称为"自引用结构"。
自引用结构用于创建数据结构,如链表、堆栈等。包含对自身引用的结构。这种情况经常出现在描述链表节点的结构中。每个节点都需要对链中的下一个节点的引用。
struct linked_list_node {
int data;
struct linked_list_node *next; // <- self reference
};