So I'm fairly new to C and pointers and I have a project for school to finish functions for adding to a linked list
this is how it looks:
TEMPLOYEE * newEmployee(const char * name, TEMPLOYEE * next)
{
TEMPLOYEE* head = NULL;
head = malloc(sizeof(TEMPLOYEE));
if(head==NULL)
{
return 1;
}
head -> m_Name = name;
head -> m_Next = next;
head -> m_Bak = NULL;
}
this works when entering name as a string for example a = newEmployee ( "Peter", a );
but when I try to add using a temporary value the m_Name in like this
strncpy ( tmp, "Victoria", sizeof ( tmp ) );
a = newEmployee ( tmp, a );
strncpy ( tmp, "Peter", sizeof ( tmp ) );
a = newEmployee ( tmp, a );
the list will change with the value so it will have two employees with the name Peter instead of Peter and Victoria and I can't find how to do this. Any help is welcome.
In the function newEmployee()
, you are doing:
head -> m_Name = name;
In both newEmployee()
call, you are passing tmp
:
a = newEmployee ( tmp, a );
a = newEmployee ( tmp, a );
So, the name
pointer of both the nodes are pointing to same location tmp
which contains the name. If you make any change in the value of tmp
, it will be reflected in both.
The in memory view would be something like this:
---------------------
|m_Name|m_Next|m_Bak|
---------------------
|
\/ tmp
-----------
| Peter |
-----------
/\
|
---------------------
|m_Name|m_Next|m_Bak|
---------------------
// Both the node m_Name is pointing to same location.
// Make any change in tmp and the changes will reflect in both the pointers
// as they are pointing to same location.
To solve this problem, you should allocate memory to m_Name
and copy the tmp
to it. You can use strdup()
to resolve this issue. In the newEmployee()
, replace this:
head -> m_Name = name;
with this:
head -> m_Name = strdup(name);
The strdup()
function returns a pointer to a new string which is a duplicate of the string passed to it. strdup() allocates a memory for the new string and returns its pointer. Make sure to free it using free()
once you are done with it. Note that strdup()
is not part of the C
Standard.
The newEmployee()
function return type is TEMPLOYEE *
but you are not returning anything from this function if the malloc
is successful. Also, if malloc
fails for some reason you are returning integer constant 1
from it which is incorrect. Instead, you should return NULL
in case of failure.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.