1

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!

Crysishy
  • 57
  • 8
  • Because you are copying _addresses_ not data. C allows you to do either. In this case you don't want to copy the address, so therefore `temp->myName = name;` is wrong. You need to study pointers before you study strings. – Lundin Dec 14 '21 at 07:45
  • 1
    I'm guessing you expect the assignment `temp->myName = name` to copy the string? It doesn't copy the string, it copies the *pointer*. After that assignment you have two pointers pointing to the same memory. – Some programmer dude Dec 14 '21 at 07:45
  • In short: Assignment copies the *value* from the right-hand side expression to the left-hand side variable. The value of a pointer is the address where it points, not the object it actually points to. Furthermore, the compiler doesn't know that `name` is a "string", all `name` really points to is a single `char`. It's a convenience that it can be treated as a pointer to the first character of a null-terminated sequence of characters. – Some programmer dude Dec 14 '21 at 07:48
  • I'm still confused, say we have char *p as a pointer. &p gives the address of p, and *p gives the value that p points to, then what is in p? And why `temp->myName = *name` also doesn't work? – Crysishy Dec 14 '21 at 08:00
  • Lets say you have `char s[] = "foo"; char *p = s;`. You can visualize it by take a pen and a piece of paper, then draw two boxes on the paper. Label one box `p` and the other `s`. Now draw an arrow from `p` to `s`. That's how pointers work. The value of the pointer variable `p` is the location of the (first element of the) array `s`. – Some programmer dude Dec 14 '21 at 08:08
  • Here gcc sees nothing of the kind. It sees that the example does not compile because a parenthesis is missing from the malloc line and that the function returns no value (beyond the missing inclusions). –  Dec 14 '21 at 09:23

0 Answers0