strcpy() 返回值 [英] strcpy() return value
问题描述
标准 C 库中的许多函数,尤其是用于字符串操作的函数,尤其是 strcpy(),共享以下原型:
A lot of the functions from the standard C library, especially the ones for string manipulation, and most notably strcpy(), share the following prototype:
char *the_function (char *destination, ...)
这些函数的返回值实际上与提供的destination
相同.为什么要为多余的东西浪费返回值?将这样的函数设为 void 或返回有用的东西更有意义.
The return value of these functions is in fact the same as the provided destination
. Why would you waste the return value for something redundant? It makes more sense for such a function to be void or return something useful.
我唯一的猜测是,将函数调用嵌套在另一个表达式中更容易、更方便,例如:
My only guess as to why this is is that it's easier and more convenient to nest the function call in another expression, for example:
printf("%s
", strcpy(dst, src));
是否有任何其他合理的理由来证明这个习语是正确的?
Are there any other sensible reasons to justify this idiom?
推荐答案
正如 Evan 指出的那样,可以做类似的事情
as Evan pointed out, it is possible to do something like
char* s = strcpy(malloc(10), "test");
例如为 malloc()ed
内存分配一个值,不使用辅助变量.
e.g. assign malloc()ed
memory a value, without using helper variable.
(这个例子不是最好的,它会在内存不足的情况下崩溃,但这个想法很明显)
(this example isn't the best one, it will crash on out of memory conditions, but the idea is obvious)
这篇关于strcpy() 返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!