很多字符串函数返回一个指针,但是返回一个指向目标的指针和返回目标的优点是什么?
#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/