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

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/50877643/

10-10 21:37
查看更多