I have a structure as below
typedef struct Mystruct{
char *name;
int telno;
struct Mystruct *nextp;
}data;
Now I malloc the structure
data *addnode;
addnode = malloc (sizeof(data));
Now I would add data to the char *name.
addnode->name = malloc (sizeof(MAX));
Question:Why is it required to malloc again?
I was under the assumption that malloc-ing the addnode will even allocate the memory for addnode->name but it is not so.
Allocating memory for
Mystructprovides enough memory for a pointer toname. At this point we have no idea how many characters will be in a name so can’t possibly allocate the memory for it.If you want to fully allocate the structure in a single allocation, you could decide on a max size for
nameand change the structure definition toOr, if you know the name when you allocate the struct, you could hide the need for two allocations from the caller by providing a constructor function