你能解释一下指针和递归结构吗?

时间:2014-08-06 09:20:13

标签: c++ c recursion struct fsm

你能解释结构内部的指针是什么意思吗?以及递归结构如何有用?你能帮我解释一下这段代码吗?它将如何在记忆中表现? 这是我的C代码:

struct State { 
unsigned long Out; 
unsigned long Time; //ms 
const struct State *Next[4];}; 

4 个答案:

答案 0 :(得分:1)

您可以参考链表示例来了解自引用指针的使用。

const struct State *Next[4]; array of pointer. 

因此它可以用于指针4自引用地址。

在以下链接中找到链接列表示例

http://www.thegeekstuff.com/2012/08/c-linked-list-example/

答案 1 :(得分:1)

如果在结构中有指针意味着指针被称为“自引用指针”。该指针将指向自己的结构。

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 
};

答案 2 :(得分:1)

这不是“递归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;

答案 3 :(得分:1)

在这种情况下,Next可以在只读地址(4个不可修改的引用)中保存4个指向相同类型(struct State)对象的指针。

一个例子:

#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 %ld\n", 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;
}