(newbie question)
Look at this struct:
struct Atom_data{
char *name;
char symbol;
double weight;
};
I want to write a function that gets a struct pointer as input, in this function with the usage of scanf()
, I want to give each member of struct a value, which one of them is string. So far I have written this function:
void data_entry(struct Atom_data* ptr){
printf("Please write the Atom's Name:\n");
ptr =(struct Atom_data *)malloc(sizeof *ptr);
ptr->name = malloc(20);
scanf("%s", ptr->name);
printf("Please write the Atom's symbol:\n");
scanf("%c", &ptr ->symbol);
printf("please write the Atom's weight:\n");
scanf("%lf", &ptr ->weight);
}
for symbol
and weight
there was no problem (when I mask the codes related to name).
But for name
there is a crash without Error.
these codes inside the function (specially codes related to name
) worked perfectly outside of the function. (I tried to test each part of them on the main function)
I learnt to write this line of code ptr =(struct Atom_data *)malloc(sizeof *ptr);
from a question about passing values to pointer! but for the line after that which is ptr->name = malloc(20);
, I just did it based on some ideas about creating dynamic memory for name
, which worked outside of the function! (Any clarification about it would show your great favour).