简体   繁体   中英

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

I am building an NFA and would like to do this by creating State structs that point to other State s. The NFA construction process requires that I keep track of which State s point to NULL and then later patch them when I know what State they should point to.

But when I update the linked list, it does not update the pointee State . I think I am not referencing and updating the NULL pointer correctly.

Here is a simplified version of the problematic code:

#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 is not 'b' because you are storing a copy of the pointer in the member of List. You are giving a State** as parameter, but you should also store it as such. You could have simply sent a State *outp and written slist->s = outp; if this were not the case.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM