c - 为什么在调用strcat时添加\001

标签 c strcat

看下面的代码:

char chs[100] = "Hello World";
char token[100];
int pos = -1;
while((current = chs[++pos]) != '"'){
      strcat(token, &current);
}

但是输出是:

H\001e\001l\001l\001o\001 \001W\001o\001r\001l\001d

有什么想法吗?

最佳答案

strcat() 在输入时需要一个以 null 结尾的字符串。所以 strcat(token, ¤t) 将从 current 的地址开始读取并继续读取,直到找到 null。只是碰巧,在 current 之后你在内存中的内容是“\001”,所以每次你执行 strcat 时,它都会将所有内容复制到 token 中。

你应该做 char current[] = "\0\0"然后用 current[0] = chs[++pos] 赋值。这样电流将始终具有空终止。

关于c - 为什么在调用strcat时添加\001,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16755552/

相关文章:

c++ - 什么是 C 中 C++ 的新/删除等价物?

c - 调用strcat时出现异常

C strcat/strcpy 到字符指针无法正确打印

c - 让: ** NO targets specififed and no makefile found.停止

c - 如何链接多个管道? (加上奇怪的 bug )

c - NULL 常量 : Guaranteed to be unique? 的整数表示

c++ - 在 C++ 中创建 .dat 文件

c++ - 使用 strcat 附加字符数组不起作用

c - 警告 : pointer targets in passing argument 2 of ‘strcat’ differ in signedness

c - 堆栈上局部变量的 GCC 符号表