开发者

pointer to pointers in C

开发者 https://www.devze.com 2023-02-18 01:07 出处:网络
I need help with pointers in C. I\'ve t开发者_C百科wo structures a struct made like this: typedef struct s{

I need help with pointers in C. I've t开发者_C百科wo structures a struct made like this:

    typedef struct s{
        s2** d;
        struct s* next;
    }s;


 typedef struct s2{
        c* fi;
        struct s2* next;
    }s2;

And I have a function like this one:

void modify(c* a, s2* b){   //c* is a pointer to a struct
    s* rd = malloc(sizeof(s);
    rd->next = NULL;
    //need also to initialize the field "d" of the "s" struct
}

This is generating error. I need the structure rd to point to b as in the example. I need to store a double pointer because s2 are linked in list-like fashion, so I need the ** pointer to have the possibility to remove the first element of the list. I was doing the assignment in the comment like rd->d = &b but when I try to deference the field "d" in a function I have an invalid memory read and I can't understand why.


I suppose the problem is this:

You pass in s2* b as an argument to modify, thus this pointer resides on the stack. Now when you assign rd->d = &b, you take that location on the stack, which will only be valid until execution leaves the scope of modify. Thus, when you dereference rd->d later on, you access that (now invalid) location on the stack, which yields garbage or a crash. (However, in this scenario, you should be able to dereference rd->d correctly while still in modify.)

Probably you'd want to alter how b is passed into modify, most likely into something like s2** b, so that you can correctly pass in a pointer to a pointer to s2 in another structure, instead of making it a pointer to s2 sitting on the stack for modify.

Basically like this:

void modify(c* a, s2** b) {
    s* rd = malloc(sizeof(s));
    rd->next = NULL;
    rd->d = b;
}

and call it like

s2* myS2 = ...;
modify(<whatever>, &myS2->next);

This should allow you to pass the location of a pointer to a s2 instance which you can store away and dereference even after modify finishes (untested, though).

0

精彩评论

暂无评论...
验证码 换一张
取 消