我的 strncat 版本将太多字符复制到目标中,我不明白为什么。
#include <stdio.h>
#define MAX_CHARS 20
void nconcatenate(char *start, char *end, int n)
{
if(sizeof start + n > MAX_CHARS)
return;
while(*start++);
start--; /* now points to the final char of start, the \0 */
int i;
for(i = 0; (*start++ = *end++) && i < n; i++);
*start = '\0';
}
int main()
{
char start[MAX_CHARS] = "str";
char *end = "ingy!";
nconcatenate(start, end, 3);
printf("start = %s\n", start);
return 0;
}
使用 3 作为'n'个输出
stringy
这是一个太多的字符。
最佳答案
可能是因为在这种情况下
(*start++ = *end++) && i < n
首先它执行 (*start++ = *end++) 然后检查 i < n。
我还没有测试过,但请检查一下。
关于c - strncat 因一个错误而关闭 - K&R C 练习 5-5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24894938/