[英]strange return behavior in strcat()
void mystrcat(char* to, const char* from) {
while (*to) to++;
while (*from) *to++ = *from++;
*to = '\0';
}
int main() {
char addthis[]= "rest of the sentence";
char start_of[] = "going to add ";
mystrcat(start_of, addthis);
cout << "after strcat(): " << start_of<< endl;
}
即使我將 function mystrcat 替換為以下,行為也是一樣的。
char* mystrcat(char* to, const char* from) {
while (*to) to++;
while (*from) *to++ = *from++;
*to = '\0';
return to;
}
對我來說很奇怪,當我調用 mystrcat 時,我沒有分配給 char* 仍然沒有編譯器的抱怨。 我在這里想念什么? 如果無論如何,你可以用 void 返回類型優化我的代碼嗎
字符串start_of
被聲明為僅足以容納初始化它的字符串。 因此,嘗試將 append 寫入到數組末尾之后。 這會調用未定義的行為。
您需要使數組足夠大以容納連接的字符串。
char start_of[50] = "going to add ";
如果您從 C 中的 function 返回,則不需要總是將返回值分配給某個變量。 其他函數,如printf
scanf
也返回值,但如果您在調用時沒有將它們分配給某個變量,它們不需要給出任何錯誤。
另外,作為旁注,您的mystrcat
function 正在以未定義的行為運行。 當它沒有分配任何進一步的空間時,您將它傳遞給兩個 char 數組並附加到第一個 char 數組本身。 所以,你應該改變它。
您應該將傳遞給 function 的第一個參數的 char 數組聲明為足夠長,以便能夠在連接后保存數據。 您可以按如下方式更改程序 -
void mystrcat(char* to, const char* from) {
while (*to) to++;
while (*from) *to++ = *from++;
*to = '\0';
}
int main() {
char addthis[]= "rest of the sentence";
char start_of[100] = "going to add ";
mystrcat(start_of, addthis);
cout << "after strcat(): " << start_of<< endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.