c - strncat 因一个错误而关闭 - K&R C 练习 5-5

标签 c string char off-by-one

我的 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/

相关文章:

ios - objective-c - char 和 unichar 之间的区别?

c++ - 预处理器中的命令连接

java - java中数组越界异常

java - 格式化日期以获取年份数字的最后两位数字(例如 : 19 from 2019)

string - 字符串中的美元符号字符

c - 从文件中读取。 C

c++字符串到char *的隐式转换匹配错误的函数签名

c - Pic16f723 尝试通过 rs 232 发送数据 tx 失败,printf 卡住了图片

c - 二维数组和函数

c++ - 在 C/C++ 中以正确的方式在文件中写入字节 [Endianness]