为什么这个指向结构的指针没有指向正确的结构?

Why does this pointer to a struct not point to the correct one?

我正在构建一个 NFA 并希望通过创建指向其他 StateState 结构来实现。 NFA 构造过程要求我跟踪哪些 State 指向 NULL,然后在我知道它们应该指向什么 State 时修补它们。

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

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

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

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

typedef struct List List;
struct List
{
    State *s;
    // 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;
    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);

    /* why is this not b? */
    //printf("%c\n", a->out->c);
    return 0;
}

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