指针作为第二个参数,而不是返回指针? [英] pointer as second argument instead of returning pointer?
问题描述
我注意到,它是在C常见的成语,以接受联合国 - 的malloc
ED指针作为第二个参数,而不是返回一个指针。例如:
I noticed that it is a common idiom in C to accept an un-malloc
ed pointer as a second argument instead of returning a pointer. Example:
/*function prototype*/
void create_node(node_t* new_node, void* _val, int _type);
/* implementation */
node_t* n;
create_node(n, &someint, INT)
而不是
/* function prototype */
node_t* create_node(void* _val, int _type)
/* implementation */
node_t* n = create_node(&someint, INT)
什么是两种方法的优点和/或缺点?
What are the advantages and/or disadvantages of both approaches?
谢谢!
修改感谢大家的答案。可供选择1动机是对我现在很清楚(我应该指出,对于选择1指针参数应 malloc分配相反的是我本来以为)。
EDIT Thank you all for your answers. The motivations for choice 1 are very clear to me now (and I should point out that the pointer argument for choice 1 should be malloc'd contrary to what I originally thought).
推荐答案
的接受的指针(其中调用者负责malloc'ing与否)内存要填写,提供了重要优势在灵活性上的返回的指针(一定malloc分配)。特别是,如果该呼叫者知道它需要使用任何的仅在一定函数返回,它可以在一个堆栈分配结构或数组的地址传递;如果它知道它并不需要重入,它可以通过在静态
结构或数组的地址 - 在这两种情况下,一个malloc /免费对得到保存,这种储蓄也悬置起来 - !)
Accepting a pointer (which the caller is responsible for malloc'ing or not) to memory to be filled in, offers serious advantages in flexibility over returning a pointer (necessarily malloc'ed). In particular, if the caller knows it needs to use whatever's returned only within a certain function, it can pass in the address of a stack-allocated struct or array; if it knows it doesn't need reentrancy, it can pass in the address of a static
struct or array -- in either case, a malloc/free pair gets saved, and such savings do mount up!-)
这篇关于指针作为第二个参数,而不是返回指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!