My program replaces all the string data types in all the nodes in the linked list

后端 未结 1 1263
Happy的楠姐
Happy的楠姐 2021-01-23 12:25

I have a program that basically adds a history(node) to the employee_record(linked list).

Here is my code:

#include 
#include 

        
1条回答
  •  礼貌的吻别
    2021-01-23 12:57

    The scanf stores strings in variables a and b. The pointers to a and b are then passed to the addjob function. Then the addjob function copies the pointers into the structure. The structure just has a pointer to the buffers. It does not have a copy of the strings. The next time that scanf is called it overwrites the contents of the buffer, and the first strings are lost.

    The solution is to make a copy of the strings, which you can do three ways

    1) declare the struct as

    struct history{
       char department1[10];
       char title1[10];
       ...
    

    and then use strcpy to copy the strings into the structure.

    2) use strdup to make a duplicate of the strings

    new->department1 = strdup(department);
    new->title1 = strdup(title);
    

    The issues with strdup: it's a non-standard function, and you have to free the memory when you're done with the strings.

    3) use malloc and strcpy to duplicate the strings

    new->department1 = malloc( strlen(department) + 1 );
    strcpy( new->department1, department );
    new->title1 = malloc( strlen(title) + 1 );
    strcpy( new->title1, title );
    

    This is slightly more work than strdup but only uses standard functions. You still have to free the memory when you're done with the strings.

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