Incompatible type for argument and uninitialised in this function

前端 未结 2 1365
旧巷少年郎
旧巷少年郎 2021-01-16 02:51

I am having an issue with one/two of my methods when I am calling it in main() and I\'m unsure why.

int main()
{
    struct list * list;

    lis         


        
相关标签:
2条回答
  • 2021-01-16 03:21

    The basic problem is in your list_init() function. In that function, list is local to the function and any changes made to list itself will not reflected to the caller function argument.

    Note: C uses pass-by-value for function parameter passing, so any changes made to the parameters themselves inside the function will not be reflected back to the argument in the caller function.

    Now in your main() code, list is an uninitialized local variable and after the call to list_init(list); it still remains uninitialized, which your compiler is rightly complaining about.

    You need to either

    • pass a pointer to the list variable in main(), accept it as a pointer to pointer to struct list (i.e., struct list ** list), allocate memory using malloc() to *list.

    • return the pointer to newly allocated memory to the caller ans assign it back to the actual pointer. You'll be needing to change the return type of list_init() in that case.

    0 讨论(0)
  • 2021-01-16 03:32

    Issue:1: Change the return type of list_init

    struct list* list_init()
    {
        list = malloc(sizeof(*list));
        if(list != NULL)
        {
            list->head = NULL;
            list->num_books = 0;
        }
        return list;
    }
    

    And call it this way in main()

    int main() {
    
        struct list * list;
    
        list = list_init();
    

    Issue:2:

    After this another issue is that in while loop every time you are taking local copy of book and using that pointer in list_add()

        struct book book1;
    

    I suggest to malloc every time, SO for every entry you will have seperate copy of book

    0 讨论(0)
提交回复
热议问题