views:

160

answers:

2

Hey all,

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

+4  A: 

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.

EricSchaefer
I would rather say '\0' or am I wrong? Zero is not the same as null character (NUL).
MartyIX
Yes, ofcourse. The escape got lost somewhere :-)
EricSchaefer
+4  A: 

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'

Martin Ingvar Kofoed Jensen
memory? Surely you mean memcpy, yes? Never mind, I'll fix it myself :-)
paxdiablo
They contain characters sorry I should have mentioned that.
ing0
@Pascal Cuoq: Defined in string.h
Martin Ingvar Kofoed Jensen
@paxdiablo: Yes, thanks mate :)
Martin Ingvar Kofoed Jensen
I have no idea what meaning is intended by "disregarding string terminating char '\0'" in this answer. Of course any zero that happens to be anywhere in `one` or `two` will be copied by `memcpy`.
Pascal Cuoq
@Pascal Cuoq: What i mean is that, memcpy will not stop when meeting a '\0' like strcpy does. Might not be that clear in my answer
Martin Ingvar Kofoed Jensen