I have a string I composed using memcpy() that (when expanded) looks like this:
char* str = "AAAA\x00\x00\x00...\x11\x11\x11\x11\x00\x00...";
I would like to print every character in the string, and if the character is null, print out "(null)"
as a substitute for '\0'.
If I use a function like puts() or printf() it will just end at the first null and print out
AAAA
So how can I get it to print out the actual word "(null)" without it interpreting it as the end of the string?
Instead of printing the string with
%s
, you will have to come up with afor
loop that checks a condition whther a given char in your char array is a\0
and then print theNULL
From C++ Reference on puts() (emphasis mine):
To process data such as you have, you'll need to know the length. From there, you can simply loop across the characters:
You have to do that mapping yourself. If you want to, that is. In C, strings are null-terminated. So, if you use a formatted output function such as
printf
orputs
and ask it to print a string (via the format specifier%s
) it'd stop printingstr
as soon as it hits the first null. There is nonull
word in C. If you know exactly how many characters you have instr
you might as well loop over them and print the characters out individually, substituting the0
by your chosen mnemonic.The draft says 7.21.6.1/8:
However, the following:
produces:
on both gcc 4.6 and clang 3.2.
However, on digging deeper:
does indeed produce the desired output:
on both gcc and clang.
Note that the standard does not mandate this:
Relying on this behavior may lead to surprises!
One of the key cornerstones of C is strings are terminated by '\0'. Everyone lives by that rule. so I suggest you not think of your string as a string but as an array of characters.
If you traverse the array and test for '\0', you can print "(null)" out in place of the character. Here is an example. Please note, your
char * str
was created either as a char array or on the stack usingmalloc
. This code needs to know the actual buffer size.