This is probably a stupid question but, I have a simple linked list struct, and a simple addNode function as following
typedef struct node {
int myInt;
char *myName;
struct node *next;
} node;
static node * addNode(char *name, int num) {
node *temp = malloc(sizeof(node);
if (temp == NULL) {
fprintf(stderr, "Out of memory.\n");
exit(1);
}
temp->myInt = num; //Correct
temp->myName = name; //Wrong
temp->myName = strdup(name); //Correct
}
My question is, why I can copy an integer by simply doing temp->myInt = num
, but I can't do the same with copying string?
Another confusion is, I understand that temp->myName
is a string pointer, so it expects to be assigned by a pointer. And name
(passed in) is also a string pointer, why myName = name
doesn't work?
Much appreciated in advance!