My question refers to the topic of C pointers. Imagine the following scenario: I have a struct variable named "stc" defined like this:
struct stc {
int data;
char ch;
}
declared in the beginning of the Main() function in my program. I would like to set the values the fields in the struct (i.e. data) using a function.
Now my question is which of the following convention is better and why?
Convention 1: Write a function the return a pointer of type stc:
struct stc *func(int d, char c)
{
stc *tmp = malloc(sizeof(stc))
tmp -> data = d;
tmp -> ch = c;
return tmp;
}
and later on free the allocated memory when the structure is no longer needed.
Convention 2: Write a function that receives a pointer to the struct and send it the address of stc
void func(stc *stcP, int d, char c)
{
stcP -> data = d;
stcP -> ch = c;
}
Thanks a lot!
The first usage could cause memory leak without care.
The second usage is better, but you use the arrow operator incorrectly, it should be:
void func(stc *stcP, int d, char c)
{
stcP -> data = d;
stcP -> ch = c;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With