c - 为什么 strcpy 返回 char * 而不是 char

标签 c

很多字符串函数返回一个指针,但是返回一个指向目标的指针和返回目标的优点是什么?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *sstrcpy ( char *destination, const char *source ){ //return a pointer to destination

    while ((*destination++ = *source++));
    *destination='\0';

return destination;
}

char sstrcpy2 ( char *destination, const char *source ){ //return destination

    while ((*destination++ = *source++));
    *destination='\0';

    return *destination;
}

int main(void){
    char source[] = "Well done is better than well said";
    char destination[40];

    sstrcpy ( destination, source );
    printf ( "%s\n", destination);



    return 0;
}

最佳答案

这个想法是为了提供链接功能的可能性。 IE。将一个函数结果作为参数传递给另一个函数结果。

sstrcpy ( destination2, sstrcpy ( destination1, source ));

至于提议的 sstrcpy2 - 它只会返回一个复制字符串的最后一个字符,在您的实现中显然是 \0,这相当大多数情况下没用。

更新:
请注意,实现 sstrcpy 是不正确的,它将返回 destination 的值,该值已移至字符串的末尾,而不是指向开头的指针它的。或者我建议保存原始指针并增加它的副本:

char *sstrcpy ( char *destination, const char *source ){ //return a pointer to destination

    char *dst = destination;
    while ((*dst++ = *source++));
    *dst='\0';

    return destination;
}

关于c - 为什么 strcpy 返回 char * 而不是 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50682897/

相关文章:

比较opencv中灰度图像的直方图

c - -pie 究竟做了什么?

C语言 : How to store data of structure in one line?

python - Python 和 C 的单一源文件

c - 在 C 文件中写入字符数组

c - Netbean IDE 上字符串数组中的不兼容指针类型警告

C++ 原型(prototype)与实现不同

自定义递归函数 |根本不返回任何值|在 C

c - 这段代码在做我想做的事吗?

c - C 中 suid-root 二进制文件中的 setegid()