看下面的代码:
char chs[100] = "Hello World";
char token[100];
int pos = -1;
while((current = chs[++pos]) != '"'){
strcat(token, ¤t);
}
但是输出是:
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/