C issue - Can't figure how to assign pointer to beginning of list

后端 未结 6 2137
猫巷女王i
猫巷女王i 2021-01-06 03:20

I have a simple assignment that the professor wants us to do. Basically to pull in some numbers from a text file and load into a linked list. I don\'t want to get to much in

6条回答
  •  醉酒成梦
    2021-01-06 04:01

    Working with code like:

    int insert_intlist( INTLIST *lst, int n )
     {
     INTLIST* lstTemp;
     lstTemp = (INTLIST *)malloc(sizeof(INTLIST));
     lstTemp->datum = n;
     lstTemp->next = lst;
     lst = lstTemp;       
     free(lstTemp);          
     }
    

    This has a couple of problems. First of all, the free(lstTemp) seems to be freeing the node that you just inserted in the list, which you probably don't want to do.

    Second, you're passing the pointer to the list into the function -- which means the function can't modify that pointer, so when you assign to the pointer, you're only changing your local copy of it.

    You have two choices: you can either pass in a pointer to that pointer (so you can modify the original pointer) or you can get clever and figure out a way to avoid needing to (but I won't give away the secret right away...)

提交回复
热议问题