Should I declare a Mystruct variable,
define the properties of Mystruct,
assign a pointer to it, and return the
pointer
Definitely not, because the variable defined in the function (in "auto" storage class) will disappear as the function exits, and you'll return a dangling pointer.
You could accept a pointer to a Mystruct
(caller's responsibility to allocate that) and fill it in; or, you can use malloc
to create a new one (caller's responsibility to free it when it's done). The second option at least lets you keep the function signature you seem to be keen on:
Mystruct *mystruct(int num, int size)
{
Mystruct *p = malloc(sizeof(MyStruct));
....
return p;
}
but it's often an inferior one -- since the caller has to have responsibilities anyway, may as well go with the first option and potentially gain performance (if the caller can use an auto-class instance because it knows the scope of use is bounded).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…