在 C 中,运行时库函数 strcpy 和 strcat 需要以零结尾的字符串。你交给他们的不是零终止的,所以这些函数会因为它们依赖于终止零来指示它们何时应该停止而崩溃。它们在 RAM 中运行,直到读取到零,这可能在 RAM 中的任何位置,包括程序外部受保护的 RAM,从而导致崩溃。在现代工作中,我们认为像 strcpy 和 strcat 这样的函数是不安全的。给他们指针的任何错误都会导致这个问题。
存在多个版本的 strcpy 和 strcat,名称略有不同,它们需要一个整数或 size_t 来指示它们的最大有效大小。例如strncat 有签名:
char * strncat( char *destination, const char *source, size_t num );
如果在你的情况下,你使用了 strncat,为最后一个参数提供 4,它就不会崩溃。
但是,您可能更愿意探索另一种选择。您可以简单地使用索引,如下所示:
char destination[5]; // I like room for a zero terminator here
for(i=0; i<4; i++)
destination[i] = grid[0][i];
这不处理零终止符,您可能会附加:
destination[4] = 0;
现在,假设您想继续,将两个单词放入一个输出字符串中。你可以这样做:
char destination[10]; // I like room for a zero terminator here
int d=0;
for(r=0; r<2; ++r ) // I prefer the habit of prefix instead of postfix
{
for( i=0; i<4; ++i )
destination[d++] = grid[r][i];
destination[d++] = ' ';// append a space between words
}
在对可能更大的目的地声明进行任何处理之后,添加一个零终止符
destination[ d ] = 0;