Concatenate two char arrays?

大兔子大兔子 提交于 2019-12-21 03:31:02

问题


If I have two char arrays like so:

char one[200];
char two[200];

And I then want to make a third which concatenates these how could I do it?

I have tried:

char three[400];
strcpy(three, one);
strcat(three, two);

But this doesn't seem to work. It does if one and two are setup like this:

char *one = "data";
char *two = "more data";

Anyone got any idea how to fix this?

Thanks


回答1:


If 'one' and 'two' does not contain a '\0' terminated string, then you can use this:

memcpy(tree, one, 200);
memcpy(&tree[200], two, 200);

This will copy all chars from both one and two disregarding string terminating char '\0'




回答2:


strcpy expects the arrays to be terminated by '\0'. Strings are terminated by zero in C. Thats why the second approach works and first does not.




回答3:


You can easily use sprintf

char one[200] = "data"; // first bit of data
char two[200] = "more data"; // second bit of data
char three[400]; // gets set in next line
sprintf(three, "%s %s", one, two); // this stores data


来源:https://stackoverflow.com/questions/3324826/concatenate-two-char-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!