memcpy question

Hello people,

I've here a warning/error which I can't solve.
I don't know why this doesn't work:
1
2
3
4
5
char strOne[] = "Ah";
    char strTwo[] = "ba";

    memcpy(strOne+2, strTwo, 2);
    cout << strOne;

How can I append a second char array?
Thanks in advance.
This is just an example. Later I want to use this on binary stuff.
The way u were using memcpy goes out of bounds on strOne since strOne is of size 2 and u were trying to write characters at strOne[2] (overwritting the null terminator) and strOne[3] which is undefined.

You could add a 3rd char strThree to hold the result of the append. U must be careful with bounds checking:
1
2
3
4
5
6
7
char strOne[] = "Ah";
char strTwo[] = "ba";
char strThree[5] = {0};

memcpy(strThree, strOne, 2);
memcpy(strThree+2, strTwo, 2);
cout << strThree;

output:
Ahba



If it's binary data then perhaps instead look into using the left-bitshift operator (<<) and then binary OR (|) the data u want to append to the end...

Last edited on
The reason why your example doesn't work is that the compiler allocates 3 characters for strOne. Two "data" characters and a null terminator.

When you copy into strOne+2 you're overwriting strOne's null terminator with 'b' and then overwriting some location in memory that is not part of strOne with 'a'. strOne is probably also no longer null terminated depending on what random character is present strOne+4.



Topic archived. No new replies allowed.