I have this basic Linked List structure:
struct node
{
char *name;
float salary;
struct node *nextNode;
};
struct list
{
struct node *firstNode;
};
This is my insert function:
void insert(struct list *pList, char *newName, float newSalary)
{
struct node *newNode;
newNode = (struct node *)malloc(sizeof(struct node));
newNode->salary = newSalary;
newNode->name = newName;
if (pList->firstNode == NULL)
{
pList->firstNode = newNode;
newNode->nextNode = NULL;
}
else
{
struct node *pos = pList->firstNode;
for(; pos->nextNode; pos = pos->nextNode);
pos->nextNode = newNode;
newNode->nextNode = NULL;
}
}
This is my main():
int main(void)
{
struct list lst;
struct list *plst = &lst;
createList(plst); //initializes the list
char name1[] = "John";
char name2[] = "Thomas";
char name3[] = "Albert";
insert(plst, name1, 1000);
insert(plst, name2, 2000);
insert(plst, name3, 3000);
}
Everything works great except for the transfer of the char array. I thought the best way to pass a char array would be by passing a pointer to the first char in the char array, but I can’t see what I did wrong.
Also, would it be better to first create a new node and then pass a pointer to this node to the insert function? It’s similar, but perhaps it is more acceptable?
This is not the right way to copy c-strings. use
strcpyorstrncpy:As @Pablo pointed out you didn’t allocate memory for string, so first allocate and then copy: