请查看以下代码:
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
有什么想法吗?
答案 0 :(得分:2)
您有未定义的行为
由于未声明current
,我猜测它是一些未初始化的字符。您的
current = chs[++pos])
设置了字符,但strcat(token, ¤t);
希望current
成为字符串,因此您在变量current
之后获得了一些垃圾。请发布更多示例代码以供进一步分析
BTW '"'
看起来错了C
答案 1 :(得分:2)
strcat()需要一个以null结尾的字符串作为输入。因此strcat(令牌和电流)将开始读取当前地址并继续运行直到找到空值。只是偶然,你在当前记忆中的内容是“\ 001”,所以你每次做strcat时都会将所有内容复制到令牌中。
你应该做char current [] =“\ 0 \ 0”然后用当前[0] = chs [++ pos]赋值。那样,当前总会有空终止。
答案 2 :(得分:0)
进行微小更改这是您的代码的有效版本:
#include <string.h>
#include <stdio.h>
int main()
{
char current[2] = { 0x0, 0x0 }; // Will be null terminated
char chs[100] = "Hello World";
char token[100] ;
int pos = -1; // Destination of strcat must also be null terminated
token[0] = '\0' ;
// String literals does not actually have " in memory they end in \0
while((current[0] = chs[++pos]) != '\0')
{
strcat(token, ¤t[0]); // Take the address of the first char in current
}
printf("%s\n", token ) ;
return 0 ;
}
strcat
期望源和目标都是以空字符结尾的字符串。在你的情况下,看起来current
刚刚在内存中有一个\001
后跟一个空终结符。