I'm learning C and this is one that I can't totally figure out. I have some code like:
typedef struct machine {
char * name;
} machine;
machine create_machine(char * name)
{
Machine machine = { .name = name };
return machine;
}
But this means that the machine is on the stack. If the user wants it on the heap they have to create a machine themselves. So I'd need a function like this instead:
typedef struct machine {
char * name;
} machine;
machine * init_machine(Machine * machine, char * name)
{
machine->name = name;
return machine;
}
The third option is to have create_machine
create a machine and put it on the heap. Then also have a teardown function:
typedef struct machine {
char * name;
} machine;
machine * create_machine(char * name)
{
Machine *machine = malloc(sizeof *machine);
machine->name = name;
return machine;
}
void machine_teardown(Machine * machine)
{
free(machine);
}
I'm leaning towards the 2nd pattern here. Have a create_machine
that returns a machine, but then also provide an "init" function that can be called. This gives the consumer the option of putting it either on the stack or the heap.
Does this sound like a reasonable conclusion? What is the pattern that most libraries take here?
Aucun commentaire:
Enregistrer un commentaire