I define a struct data type:
typedef struct LinkNode LinkNode;
struct LinkNode {
char *name;
LinkNode *next;
};
And call it in main():
Example1:
int main()
{
LinkNode *pnode = (LinkNode *) malloc(sizeof(LinkNode));
scanf("%s", pnode->name);
...
free(pnode);
return 0;
}
It doesn’t work, unless add one line: Example 2
int main()
{
LinkNode *pnode = (LinkNode *) malloc(sizeof(LinkNode));
pnode->name = (char *) malloc(sizeof(char));
scanf("%s", pnode->name);
...
free(pnode);
return 0;
}
But the following code works: Example 3
int main()
{
LinkNode *pnode = (LinkNode *) malloc(sizeof(LinkNode));
pnode->name = "Jim";
...
free(pnode);
return 0;
}
So what’s the problem? I have been assigned memory to pnode, why scanf() doesn’t work? I’m using VS2010.
Thanks!
When you use
scanf, you need an allocated block of memory to write to. When you allocate memory fornamewithmallocit works, even if you are just allocating one byte (like @billz pointed out), because you have a valid memory address now. You have to allocate enough memory though, or you will overwrite something and cause trouble sooner or later.When you assign a string literal to the pointer
name(pnode->name = "Jim";), you are merely setting it to the address of a hardcoded string in memory. If you try to modify it bad things will happen, so never do this unless you are using a const pointer.Bottom line,
nameis just a pointer, to do anything with it, you need it to point to something valid.