[英]Why does this pointer to a struct not point to the correct one?
我正在建立NFA,并希望通过创建指向其他State
的State
结构来做到这一点。 NFA的构建过程要求我跟踪哪个State
指向NULL
,然后在我知道它们应指向哪个State
时对其进行修补。
但是,当我更新链表时,它不会更新pointee 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.