当前位置: 技术问答>linux和unix
strcat函数的疑问
来源: 互联网 发布时间:2016-03-20
本文导语: #include #include int main(int argc, char *argv[]) { char *string; string = strcat(argv[1], " "); string = strcat(string, argv[2]); string = strcat(string, " "); string = strcat(string, argv[3]); printf("%sn", st...
#include
#include
int main(int argc, char *argv[])
{
char *string;
string = strcat(argv[1], " ");
string = strcat(string, argv[2]);
string = strcat(string, " ");
string = strcat(string, argv[3]);
printf("%sn", string);
return 0;
}
假定程序编译后命名为echo,那么“./echo i love you baby”后回车
出来的结果不是预想的“i love you”,而是“i you”(i和you之间是2个空格)
把代码用循环来实现,然后输入更多的文字,后面显示均正常,就是第二个不能显示
请问哪里有错误导致这种情况的出现呢?
#include
int main(int argc, char *argv[])
{
char *string;
string = strcat(argv[1], " ");
string = strcat(string, argv[2]);
string = strcat(string, " ");
string = strcat(string, argv[3]);
printf("%sn", string);
return 0;
}
假定程序编译后命名为echo,那么“./echo i love you baby”后回车
出来的结果不是预想的“i love you”,而是“i you”(i和you之间是2个空格)
把代码用循环来实现,然后输入更多的文字,后面显示均正常,就是第二个不能显示
请问哪里有错误导致这种情况的出现呢?
|
不好意思,还是漏掉了argv[3]最后的那个''
还没有明白为什么吗?
7fffffffecee
7fffffffecf0
7fffffffecf5
从7fffffffecee (argv[1])开始的内存布局:
还没有明白为什么吗?
7fffffffecee
7fffffffecf0
7fffffffecf5
从7fffffffecee (argv[1])开始的内存布局:
argv[1]-------argv[2]----------------------------argv[3]-----------------------------
---|------------|----------------------------------|---------------------------------
-------------------------------------------------------------------------------------
|'I' |'' |'l' |'o' |'v' |'e' |'' |'y' |'o' |'u' |'!' |'' |
-------------------------------------------------------------------------------------
string = strcat(argv[1], " ");执行后
-------------------------------------------------------------------------------------
|'I' |'x20'|'' |'o' |'v' |'e' |'' |'y' |'o' |'u' |'!' |'' |
-------------------------------------------------------------------------------------
string = strcat(string, argv[2]);执行后
-------------------------------------------------------------------------------------
|'I' |'x20'|'' |'o' |'v' |'e' |'' |'y' |'o' |'u' |'!' |'' |
-------------------------------------------------------------------------------------
string = strcat(string, " ");执行后
-------------------------------------------------------------------------------------
|'I' |'x20'|'x20'|'' |'v' |'e' |'' |'y' |'o' |'u' |'!' |'' |
-------------------------------------------------------------------------------------
string = strcat(string, argv[3]);执行后
-------------------------------------------------------------------------------------
|'I' |'x20'|'x20'|'y' |'o' |'u' |'!' |'' |'o' |'u' |'!' |'' |
-------------------------------------------------------------------------------------