I need to concatenate some strings, and I need to include NULL bytes. I don't want to treat a '\0' as a terminating byte. I want to save my valuable NULL bytes!
In a code example, if
char *a = "\0hey\0\0";
I need to printf in a format that will output "\0hey\0\0".
-AUstin
How about:
If you want a 'printf-like' function to use this when you specify
%s
in a format string you could include the above code in your own function. But as @Neil mentioned, you'll struggle finding an alternative to looking for null bytes to determine the length of strings. For that I guess you could use some kind of escape character.The issue here is that the length of the string
a
cannot be easily determined. For example, your code.... allocates seven bytes to the string, the last being the NULL terminator. Using a function like
strlen
would return 0.If you know the precise length of the string, then you can write or iterate over the bytes thus:
But you have to know about the 6.
The alternative is not to use NULL-terminated strings, and instead implement an alternative storage mechanism for your bytes; for example a length-encoded array.
Graceless, but hopefully you get the idea.
Edit: 2011-05-31
Rereading the question I just noticed the word "concatenate". If the NULL characters are to be copied faithfully from one place in memory to another (not backslash-escape), and you know the total number of bytes in each array beforehand, then you can simply use
memcpy
.