什么将空字符串复制到另一个字符串?

What will empty string copy to another string?

我刚开始学习 C 编程。谈到字符串时,我对函数 'strcpy' 感到困惑。我尝试交换第一个参数和第二个参数的位置。当我运行程序时,它只显示一个'S'。这是什么意思?

char s2[ ]= "Hello";
char s1[10];
strcpy(s2, s1);
printf("Source string = %s\n", s2);
printf("Target string = %s\n", s1);

我以为输出会是空的。但它只是显示了一个 'S'.

根据 printf 语句,您混淆了 strcpy 的参数。

就像现在一样,您正在将 s1 复制到 s2。然而,数组 s1 未初始化,因此它包含的值是 indeterminate.

复制s2s1,切换参数:

strcpy(s1, s2);

如果保持原样,您需要将 s1 显式设置为空字符串以获得一致的结果。

char s1[10] = "";

在 C 中,字符串以零结尾。这意味着空字符串是包含单个 "zero terminator" 字符的字符串。

复制空字符串时,复制单个 "zero terminator" 字符。目标字符串仍然有一个地址("pointer to the strings chars" 将指向零终止符)并且指向字符串的指针不会为 NULL。