Thread: Can someone help me?

  1. #1
    Registered User
    Join Date
    Feb 2019
    Posts
    3

    Can someone help me?

    I know there is a problem in realloc but I don't know why

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    struct mystruct
    {
        int valore;
        struct mystruct *next;
    };
    typedef struct mystruct Struct;
    
    
    void crea_lista(Struct *mystruct, int *dim);
    void modifica_lista();
    void elimina_lista();
    void aggiugni_lista();
    
    
    int main()
    {
        int i,dim=0;
        Struct *strutture;
    
    
        for(i=0;i<2;i++)
            crea_lista(strutture,&dim);
    
    
        return 0;
    }
    
    
    void crea_lista(Struct *mystruct, int *dim)
    {
        int newdim=*dim+1;
    
    
        printf("%d - ",newdim);
    
    
        if(newdim==1)
            mystruct=malloc(newdim*sizeof(Struct));
        else
            mystruct=realloc(mystruct,newdim*sizeof(Struct));
    
    
        *dim=newdim;
    
    
        printf("%d\n",sizeof(mystruct));
    
    
    }

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Do you realize that you're passing that pointer into the crea_lista() function by value? Which means that any changes to the pointer is lost when the function returns.

  3. #3
    Registered User
    Join Date
    Feb 2019
    Posts
    3
    So, please, how can I resolve it?

  4. #4
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Try passing the pointer by reference.:

    Code:
    void crea_lista(Struct **mystruct, int *dim);
    ...
        for(i=0;i<2;i++)
            crea_lista(&strutture, &dim);
    ...
    You'll also need to modify the function to properly reference the pointer.

  5. #5
    Registered User
    Join Date
    Feb 2019
    Posts
    3
    thank you very much

Popular pages Recent additions subscribe to a feed

Tags for this Thread