I have a function which takes a structure as a parameter, like:
add_new_structure(structure s);
then store it inside
structure structure_list[200];
question:
1. when I want to use the structure, I have a function like
structure *getStructure(int id)
{
return &structure_list[id];
}
is it gonna work if I add one structure like this:
void init()
{
structure test;
memset(&test,0,sizeof(structure));
add_new_structure(test);
}
and then call getStructure from another function? like this:
void anotherFunction()
{
structure *got_test = getStructure(0);
}
because I remember I can’t have local variable and then call it from another function right?
2.is it better to just store it like this?
change the add_new_structure() parameter to structure *s;
then store it inside
structure *structure_list[200]; by calling add_new_structure(&test);
3. which one is better? or what is the right way to do it?
The first approach, i.e. you pass the instance directly as a parameter, works. Because the whole instance is copied when calling the function. And what you store is a copy of the original struct instance.
However, you can’t pass and store a pointer to a local variable. The problem you mentioned above will occur in this case.
IMHO, neither of the above approaches are right. The first approach will introduce too much overhead when passing parameters to the function. While the second one cannot achieve what you want.
You’d better dynamically allocate memory with
malloc/callocand store the pointer in the array. Don’t forget to release the object at the end of use in case of memory leak. Like this: