[英]C concat two small strings to one larger string
我正在尝试创建一个将两个字符串连接在一起的程序。 我的代码创建了一个char[]
,该字符串由两个字符串strcat
插入。 结果是混乱的垃圾。 知道发生了什么事吗? 我会想象char[]
已经堆满了垃圾,当我尝试concat
,但我不知道。
#include <stdio.h>
#include <string.h>
int main(){
char* s1 = "this";
char* s2 = "that";
char s3[9];
int i;
for(i = 0; i < 4; i++){
printf("%c\n", s3[i]);
}
strcat(s3, s1);
for(i = 0; i < 4; i++){
printf("%c\n", s3[i]);
}
strcat(s3, s2);
for(i = 0; i < 4; i++){
printf("%c\n", s3[i]);
}
}
输出:
@
@
t
@
t
您要么必须设置s3 [0] ='\\ 0'; 否则您必须将strcpy用于第一个。
s3 [0] ='\\ 0';
#include <stdio.h>
#include <string.h>
int main(){
char* s1 = "this";
char* s2 = "that";
char s3[9];
int i;
s3[0] = '\0';
for(i = 0; i < 4; i++){
printf("%c\n", s3[i]);
}
strcat(s3, s1);
for(i = 0; i < 4; i++){
printf("%c\n", s3[i]);
}
strcat(s3, s2);
for(i = 0; i < 4; i++){
printf("%c\n", s3[i]);
}
}
的strcpy
#include <stdio.h>
#include <string.h>
int main(){
char* s1 = "this";
char* s2 = "that";
char s3[9];
int i;
for(i = 0; i < 4; i++){
printf("%c\n", s3[i]);
}
strcpy(s3, s1);
for(i = 0; i < 4; i++){
printf("%c\n", s3[i]);
}
strcat(s3, s2);
for(i = 0; i < 4; i++){
printf("%c\n", s3[i]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.