gpt4 book ai didi

c - 为什么我首先必须在 strcat() 之前使用 strcpy()?

转载 作者:太空狗 更新时间:2023-10-29 16:25:11 27 4
gpt4 key购买 nike

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

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.

关于c - 为什么我首先必须在 strcat() 之前使用 strcpy()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18838933/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com