Possible Duplicate:
pointer as second argument instead of returning pointer?
I see this a lot:
Monkey* test = malloc(sizeof(Monkey));
Monkey_New(test);
Wouldn’t it be cleaner to have the init function return the pointer?
Monkey* test = Monkey_New();
Why is it frequently done in the first way?
The two designs are functionally extremely different. The one you’re asking about puts the burden of allocation on the caller. This has a huge advantage that dynamic storage (
malloc) can be avoided if the object does not have to out-live the caller; it can be stored in an automatic variable. This also means that, assuming the init function does not have to obtain further resources, you can have a failure-free API where the caller does not have to check for failure. On the other hand, it requires that the definition (at least the size) of the structure be exposed to the calling module, which means the caller must be recompiled if the library code is updated to use an object of a larger size; thus it can be negative for shared libraries intended to have a long-term stable ABI.In the alternative design you pointed out, the burden of obtaining storage is on the callee (library function), and it must use dynamic storage (
malloc) since automatic storage would not survive the return to the caller. This is more abstract and cleaner,