I have been given this function prototype void create_smth(smth* s)
and it is asked that this function creates, initializes and returns a smth variable. Is this even possible? To my knowledge I would need a double pointer to do such a thing.
What I am doing in this function is
s=(smth*)malloc(sizeof(smth));
This is probably the mistake.
In my main I have tried
smth* smth1=NULL;
create_smth(smth1);
and
smth smth1;
create_smth(&smth1);
but my code keeps crashing (Segmentation fault; core dump). I am starting to wonder if it is an instructors mistake but feel stupid to ask him straight up but the excercise requires what I stated above. Thanks everyone.
CodePudding user response:
Looks like instructor's mistake to me. You are correct that the void create_smth(smth* s)
prototype cannot return a value, either in the traditional return
sense (it is void
), or using a double pointer. The only two ways to do this:
smth* creat_smth()
{
smth* mySmth = malloc(sizeof *mySmth);
// check malloc return valid pointer, initialize fields with mySmth->
return mySmth;
}
int main(void)
{
smth* smth1 = creat_smth();
...
return 0;
}
or
void creat_smth(smth** mySmth)
{
*mySmth = malloc(sizeof **mySmth);
// check malloc returned valid pointer, initialize fields with (*mySmth)->
}
int main(void)
{
smit* smth1;
creat_smth(&smth1);
...
return 0;
}
CodePudding user response:
It’s worth asking your instructor for clarification. That said, it’s at least somewhat common to have functions that follow the pattern int init_smth(smth *x)
— but note the name: such functions are usually called init_•
, not create_•
(because it doesn’t create the storage for this object, it just fills it).
This makes sense when it’s expected that stack-allocating the struct is the right thing to do. Instead of using malloc
, the user would pass a pointer to a locally allocated structure:
smth my_smth;
init_smth(&my_smth);
And inside init_smth
some moderately complex initialisation would take place (but again without malloc
: the memory for the object is already allocated).
However, even then it’s more common for the function to return a status code indicating success (hence the return type int
in my prototype above).