How to initialize a struct inside a function that is given a variable as reference

92 views Asked by At

I'm still somewhat new to c and I'm trying to allocate some memory to a struct inside a function and pass it around by reference.

My solution doesn't work because the struct im initializing there doesnt get passed to the other functions and im getting errors for trying to access memory, that isnt allocated.

Heres the problematic code:


#include <stdlib.h>

typedef struct list list;

struct list {
     int x;
};

void init_list(list* mylist){
    mylist = malloc(sizeof(list));
    mylist->x = 1;
}

void free_list(list* mylist){
    free(mylist);
}

main(){
    list mylist;
    init_list(&mylist);

    //use the value of x for something

    free_list(&mylist); 
}

I tried doing this:

init_list(list* mylist){
   list *temp = malloc(sizeof(list));
   -initiliaze variables-
   *mylist = *temp
}

In that case the other functions can Access the struct but i can't free it because i dont have the right pointer. It just says "free() invalid size" when i try to run it.

So what is the right way of allocating memory and passing the adress around in this case? Also i know that i could just return it but i want to know if and how it is possible by reference.

Also im using clang to compile.

Thanks in Advance.

1

There are 1 answers

0
Hello World On

When you call init_list(), it allocates a memory block the size of struct list, and sets the value of x to be 1. You're good there. But you seem to have a bit of a problem with the input to your function. When you pass a parameter to a function in C, you really pass a copy of it. Changing the value inside the function does not change the value back in main(). This means that what you pass to your function must be a refernce to what you want your function to change. In this case, you want your function to change the pointer to a struct list when you call malloc(). The work-around you're looking for is something like this:

int main(void) {
list *pointer_to_list; //declares pointer, NOT a struct
init_list(&pointer_to_list); //passes the reference value of the pointer (essentially a 'struct list**')
free_list(pointer_to_list);
}

where init_list() is defined as:

void init_list(list **mylist) {
*mylist = malloc(sizeof(list)); //sets the pointer called pointer_to_list in main() to the ouput of malloc()
(**mylist).x = 1;

//Note that we never change the value of mylist
//because it won't change anything in main() anyway
}