strcpy函式的實現

2021-06-20 19:43:04 字數 854 閱讀 6621

**:感謝分享!

[cpp]view plain

copy

char *my_strcpy(char *dst,const

char *src)    

如果注意到:

1,檢查指標有效性;

2,返回目的指標des;

3,源字串的末尾 '\0' 需要拷貝。

寫出上面實現函式就不在話下。

然而這樣的實現沒有考慮拷貝時記憶體重疊的情況,下面的測試用例就能使呼叫my_strcp函式的程式崩潰:

[cpp]view plain

copy

char str[10]="abc";  

my_strcpy(str+1,str);  

然而呼叫系統的strcpy函式程式正常執行,列印str結果為「aabc」!可見系統strcpy函式的實現不是這樣的。

strcpy的正確實現應為:

[cpp]view plain

copy

char *my_strcpy(char *dst,const

char *src)    

[cpp]view plain

copy

void * my_memcpy(void *dst,const

void *src,unsigned int count)  

}  else

//源位址和目的位址重疊,高位元組向低位元組拷貝

}  return ret;  

}  

兩者結合才是strcpy函式的真正實現吧。

strcpy函式的實現

大家一般認為名不見經傳strcpy函式實現不是很難,流行的strcpy函式寫法是 cpp view plain copy char my strcpy char dst,const char src 如果注意到 1,檢查指標有效性 2,返回目的指標des 3,源字串的末尾 0 需要拷貝。寫出上面實現...

strcpy函式的實現

strcpy函式的實現 已知strcpy函式的原型是 char strcpy char dst,const char src 實現strcpy函式 解釋為什麼要返回char 假如考慮dst和src記憶體重疊的情況,strcpy該怎麼實現 1.strcpy的實現 char strcpy char ds...

strcpy函式的實現

strcpy函式的實現 大家一般認為名不見經傳strcpy函式實現不是很難,流行的strcpy函式寫法是 cpp view plain copy char my strcpy char dst,const char src 如果注意到 1,檢查指標有效性 2,返回目的指標des 3,源字串的末尾 0...