Copying a string with nulls inside

381 views Asked by At

I want to copy a string in C (Windows) that contains nulls in it. I need a function to which I will pass buffer length so that the NULL characters will be meaningless. I found StringCbCopy function but it still stops at the first NULL character.

3

There are 3 answers

1
Blrfl On BEST ANSWER

Since you know the length, use memcpy().

0
PurpleOak On

Here is a quick bit of code that may help:

char array1[5] = "test", array2[5];
int length = 5;
memcpy(array2, array1, length*sizeof(char));
//the sizeof() is redundant in this because each char is a byte long
//but it is useful if you are working with other datatypes

memcpy probably will become your best friend for situations like this.

1
Darkhydro On

It should be very easy to write your own function to do this. If you know the length of the string, just create a char[] or char* with the specified length, and copy characters one by one.