为什么指向结构的指针不指向正确的结构?

时间:2015-02-02 01:00:14

标签: c pointers

我正在构建NFA,并希望通过创建指向其他State的{​​{1}}结构来实现此目的。 NFA构建过程要求我跟踪哪个State指向State,然后在我知道他们应指向的NULL时对其进行修补。

但是当我更新链表时,它不会更新指针State。我想我没有正确引用和更新State指针。

以下是有问题的代码的简化版本:

NULL

1 个答案:

答案 0 :(得分:1)

a->out->c不是'b',因为您将指针的副本存储在List的成员中。您将State**作为参数,但您也应该将其存储为参数。如果情况并非如此,您可以简单地发送State *outp并撰写slist->s = outp;

#include <stdio.h>
#include <stdlib.h>

typedef struct State State;
struct State
{
    char c;
    State *out;
};

typedef struct List List;
struct List
{
    State **s; //<--- HERE
    // has a next member that is irrelevant here.
};

State *State_new(char c, State *out)
{
    State *s;
    s = malloc(sizeof(*s));
    s->c = c;
    s->out = out;
    return s;
}

void *List_new(State **outpp)
{
    List *slist = malloc(sizeof(*slist));
    /* 
     * Dereference the pointer to a pointer of a State
     * to get a pointer to a state
     */
    slist->s = outpp; //<<--- HERE
    return slist;
}

int main()
{
    State *a = State_new('a', NULL);
    List *l  = List_new(&(a->out));

    /* This printf() will result in a seg fault, since a->out is NULL. */
    //printf("%c\n", a->out->c);

    /* change what State struct is pointed to by l */
    *l->s = State_new('b', NULL);

    printf("%c\n", a->out->c);
    return 0;
}