[英]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.