A: 返回的指针应该指向一个静态分配的缓冲(像在问题7.5a中的回答),或者由调用者传入的缓冲,或者由malloc获得的俄内存,但不是一个局部(自动)数组。
例如,由调用者传递用于存放结果的空间:
char *itoa(int n, char *retbuf) { sprintf(retbuf, "%d", n); return retbuf; } ... char str[20]; itoa(123, str);
使用malloc:
#includechar *itoa(int n) { char *retbuf = malloc(20); if(retbuf != NULL) sprintf(retbuf, "%d", n); return retbuf; } ... char *str = itoa(123);
(在后一个例子中,调用者必须记得在不再使用时,释放返回的指针指向的内存。)
同时参见问答20.1。
补充链接:更多阅读。
(This Chinese translation isn't confirmed by the author, and it isn't for profits.)
Translator : jhlicc@gmai1.c0m
Origin : http://www.c-faq.com/malloc/retaggr2.html