为什么我必须先使用 strcpy(),然后再使用 strcat()?

2023-11-24

为什么此代码会产生运行时问题:

char stuff[100];
strcat(stuff,"hi ");
strcat(stuff,"there");

但这不是吗?

char stuff[100];
strcpy(stuff,"hi ");
strcat(stuff,"there");

strcat将查找空终止符,将其解释为字符串的结尾,并在此处附加新文本,覆盖进程中的空终止符,并在串联末尾写入新的空终止符。

char stuff[100];  // 'stuff' is uninitialized

空终止符在哪里?stuff未初始化,因此它可能以 NUL 开头,或者可能在其中任何地方都没有 NUL。

在 C++ 中,您可以这样做:

char stuff[100] = {};  // 'stuff' is initialized to all zeroes

现在您可以执行 strcat,因为“stuff”的第一个字符是空终止符,因此它将附加到正确的位置。

在 C 中,您仍然需要初始化“stuff”,可以通过以下几种方式完成:

char stuff[100]; // not initialized
stuff[0] = '\0'; // first character is now the null terminator,
                 // so 'stuff' is effectively ""
strcpy(stuff, "hi ");  // this initializes 'stuff' if it's not already.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么我必须先使用 strcpy(),然后再使用 strcat()? 的相关文章

随机推荐