[英]why strcpy return char * and not 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;
}
這樣做的想法是使鏈接功能成為可能。 即將一個函數結果作為參數傳遞給另一函數。
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;
}
錯誤1:您返回字符串的結尾,而不是開頭。
錯誤2:您在末尾添加了2個空終止符,而不是1個。
正確的實現應遵循以下方面:
char* sstrcpy (char*restrict dst, const char*restrict src)
{
char* original = dst;
for(*dst = *src; *src != '\0'; dst++, src++)
{
*dst = *src;
}
return original;
}
其中restrict
是與調用方的合同,其中dst
和src
不重疊。 請注意,這可能仍然是幼稚的實現-對於小型微控制器來說很好,但是,對於32位系統的strcpy庫實現,它們將與對齊的數據塊一起使用。
返回指向目標的指針和返回目標的優點是什么?
毫無優勢。 標准庫充滿了奇怪之處。 這允許兩種無意義的混淆:
// Bad code, do not use!
/*1*/ str = strcpy(str, src); // pointless and potentially dangerous
/*2*/ strcpy(str2, strcpy(str1, src)); // pointless and potentially dangerous
反過來,這會導致參數評估中的副作用導致錯誤,因此很危險。 不要這樣胡扯。 正確的版本是:
/*1*/ strcpy(str, src);
/*2*/ strcpy(str1, src);
strcpy(str2, str1);
后者版本更安全,更易於閱讀。 產生的機器代碼將是相同的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.