(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).
void data_entry(struct Atom_data* ptr){
printf("Please write the Atom's Name:\n");
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
:
Some other resources, that might be of interest to you:
• Difference between pointer and array
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments