gpt4 book ai didi

c - 为什么指向结构的 this 指针没有指向正确的结构?

转载 作者:行者123 更新时间:2023-11-30 15:24:44 26 4
gpt4 key购买 nike

我正在构建一个 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;
}

关于c - 为什么指向结构的 this 指针没有指向正确的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28269780/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com