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.
When you call
init_list(), it allocates a memory block the size ofstruct 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 inmain(). 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 astruct listwhen you callmalloc(). The work-around you're looking for is something like this:where
init_list()is defined as: