\0char *strcpy(char *to, const char *from) { char *save = to; while (*from) { *save = *from; ++save; ++from; } return to; // 缺少 *save = '\0',導致輸出亂碼 }
運行結果:hello,world!"(後跟隨機垃圾字符)。
while ((*save = *from)) { ++save; ++from; }
while (*from) { *save = *from; ++save; ++from; } *save = '\0';
char *strcpy(char *to, const char *from) { char *save = to; for (; (*to = *from) != '\0'; ++from, ++to); return save; }
char *strcpy1(char *to, const char *from) { int i; for (i = 0; (to[i] = from[i]); ++i); return to; }
char *strcpy2(char *to, const char *from) { char *save = to; while ((*to++ = *from++) != '\0'); return save; }
\0 是 C 字符串的邊界標記,缺之則所有字符串函數(printf、strlen、strcat…)失效。strcat(strcpy(dest, src), "tail"))。strcpy 不檢查邊界,生產代碼首選 strncpy、strlcpy 或 C++ std::string。memmove。int main() { char c[20]; char *s = "hello,world!"; strcpy(c, s); printf("%s\n", c); // 正確輸出 hello,world! return 0; }