Search code examples
cstructurerealloc

Realloc a table of structures that has table in it


I am trying to write a programe that will store data in a table of structures. My problem is that i can't figure out why my realloc isn't working.

I am trying to realloc a table that is in a table of structures (sounds confusing, i know), but it won't work. Here is the part of my program i have a problem with:

typedef struct {
    int *node;
    int l;
}przejscie_t;

void czytaj(przejscie_t **graf, int vp, int vk){

    *graf=realloc(*graf,(vp+1)*sizeof(przejscie_t));
    (*graf)[vp].l=1;
    (*graf)[vp].node=realloc((*graf)[vp].node,(*graf)[vp].l*sizeof(int)); //it crashes here
    (*graf)[vp].node[(*graf)[vp].l]=vk;
    
}

Solution

  • (*graf)[vp].node=realloc((*graf)[vp].node,(*graf)[vp].l*sizeof(int)); //it crashes here
    

    realloc needs a valid initialized pointer as first parameter (or NULL, in this case it stands as if malloc was called), since (*graf)[vp].node is not initialized you are passing garbage.