简体   繁体   中英

Access struct member from pointer

I've some problems of segmentation fault with this code:

void init(int max, pile * p) {
    p = (pile *)malloc(sizeof(pile));
    if(p){
        p->nbElemPresent = 0;
        p->maxElem       = max;
        p->tete          = (data *)malloc(max * sizeof(data));
    }
}

short int vide(pile * p) {
    if(p->maxElem == 0) {return 1;}
    return 0;
}

my function vide return me segfault.. I don't know how to access to struct member from the p pointer.

The main program:

pile * p;
init(5, p);
printf("%d", vide(p));

ty.

C takes parameters by value, that means that pointer p is copied when you pass it to init(). p in the function is a completely new variable and if its value is changed that doesn't change the value of p passed to the function.

You should pass its address:

init(5, &p);

void init(int max, pile** p) {
    *p = malloc(sizeof(pile));
    if(*p){
    (*p)->nbElemPresent = 0;
    ....
    }
}

Note the unusual parenthesis (*p)->nbElemPresent , this is done because -> operator has a higher precedence, yet we want to dereference the p first.

as already said, p is a new variable in your init function. other than the other answers suggested, i'd rather suggest not taking p as an argument at all, but instead returning it:

pile* init(int max) {
  pile *p = (pile *)malloc(sizeof(pile));
  ...
  return p;

}

and in your main function:

pile * p = init(5);
printf("%d", vide(p));

As said by barak manos, your problem lies in init . C pass parameters by value so let's imagine :

  • you set a pointer to pile to NULL ( pile *p = NULL; )
  • you pass it to init ( init(p); )
  • in init you alloc a pile and affect is to the local copy of p
  • on return from init, p is still NULL and you have a memory leak since you have no longer any pointer to the allocated pile

That's the reason why you should write :

void init(int max, pile ** p) {
    pile *lp = *p = (pile *)malloc(sizeof(pile));
    if(*p){
        lp->nbElemPresent = 0;
        lp->maxElem       = max;
        lp->tete          = (data *)malloc(max * sizeof(data));
    }
}

Now you use :

pile *p;
init(&p);

and on return p points to the allocated pile.

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