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

约翰娜

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

#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;
}
尤金·S。

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

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;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么我可以在函数后返回“ int”而不是“ char *”?

为什么sizeof(char + char)返回4?

了解char *,char []和strcpy()

为什么要使用Char而不是String?

为什么strtok使用char *而不是const char *?

C API:为什么函数使用带有缓冲区+大小的returnParameters而不是返回char *

为什么我可以将char *隐式转换为const char *,而不是无符号char *

返回一个char数组,而不是const char *

在char上使用toupper返回char的ascii号,而不是字符?

C ++程序返回数字而不是Char

为什么我的函数在应返回char时返回垃圾?

为什么strcmp返回int但不返回char?

内存浪费?如果main()应该只返回0或1,为什么main是用int而不是short int甚至char声明的?

为什么在Vaadin中,PasswordField使用String而不是char []?

为什么const int需要extern而不是const char *

为什么我的char打印为数字而不是字符?

为什么TextWriter.Write(char)不是抽象的?

为什么这个结构数组会覆盖 char * 而不是 int?

结构中的char数组-为什么strlen()返回正确的值?

为什么CHAR和VARCHAR在MySQL中返回相同的长度?

为什么to_char和to_date返回不同的结果

为什么* p为(char * p =“ hello world”)返回整数

为什么将fgetc()返回到char iso int?

为什么我的char *复印机返回不同的东西?

为什么char * foo()返回空字符串?

为什么char的Convert.ToInt32返回ascii代码?

为什么要返回这个值?C ++ int / char混淆

为什么需要静态char *而不是static char **进行常量初始化

为什么 std::string 实现为 `char` 的 basic_string 而不是 `unsigned char`