// Define Person
typedef struct Person {
char *name;
int age;
} person_t;
// Init person in heap
person_t *create_person_v1(char *name, int age)
{
person_t *person = calloc(1, sizeof(person_t));
person->name = name;
person->age = age;
return person;
}
// Init person on stak? a static struct I guess?
person_t create_person_v2(char *name, int age)
{
return (person_t) {name, age};
}
The code above has a definition of Person and two helper functions for its further initialization.
I don't really understand the difference between them, and what are the benefits of having each?
Is it something more than just accessors ->
and .
?
CodePudding user response:
The last function does not allocate a static structure, but a structure on the stack. There is two kind of memory for your programm, heap and stack. static is an other keyword (which have more than 1 use, depending on where they are used, but it's not the current subject).
heap allocations use more ressources than stack allocations, but are not tied to scopes where they are used. You can manipulate structures heap allocated between functions without having to think they can be "automatically freed" because the scope on which they are tied disappear (aka : initial function returned).
An example would be a linked list. You can't rely on stack allocations to build a linked list of structures.
Heap allocations can fail, you always have to check if malloc, calloc and cie, does not return NULL.
Stack allocations doesn't fail like that. If you sucked all your stack, your programm will just crash. ( Or do some fancy things, it is undefined bahavior ). But you can't recover from that.
stack allocated memory is "freed" on function returns. not heap allocated memory. But you have to free it by hand (with function free)