void data_entry(struct Atom_data* ptr){
printf("Please write the Atom's Name:
");
ptr =(struct Atom_data *)malloc(sizeof *ptr);
Will do nothing useful for you.
You are setting ptr
to a dynamically allocated piece of memory, but it won't change the pointer you pass into the function:
struct Atom_data *data = NULL;
data_entry(data);
// data will still be NULL
If the desired behaviour is in fact, to set a pointer from within the function you need to use a "pointer to a pointer" like this:
void data_entry(struct Atom_data **ptr) {
*ptr = malloc(sizeof(** ptr));
}
And then later:
struct Atom_data *data = NULL;
data_entry(&data);
// data will not be NULL (if malloc worked.)
However, this is unecessarily complicated, the common way to do it is like this:
struct Atom_data *data_entry() {
struct Atom_data *ptr = malloc(sizeof(* ptr));
// check for NULL pointer returned by malloc (out of memory)
if (!ptr) return NULL;
// initalisation
ptr->name = NULL;
ptr->symbol = 'a';
ptr->weight = 0;
return ptr;
}
And use it like this:
struct Atom_data *data = data_entry();
Of course, if you want to initialize the struct within the function, you'll need to pass those as well:
struct Atom_data *data_entry(char *name, char symbol, double weight)
It really depends on how you want to initialize the struct.
Note: memory allocated with malloc
can/should be "released" (or given back to the OS) with free
. Failing to do so, can lead to memory leaks.
Also, be careful with scanf
:
? Disadvantages of scanf
? Reading a string with scanf
Some other resources, that might be of interest to you:
? Difference between pointer and array
? Difference between char * and char []
? Difference between "." and "->".