Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The issue here is that the length of the string <code>a</code> cannot be easily determined. For example, your code..</p> <pre><code>char *a = "\0hey\0\0"; </code></pre> <p>.. allocates seven bytes to the string, the last being the NULL terminator. Using a function like <code>strlen</code> would return 0.</p> <p>If you know the precise length of the string, then you can write or iterate over the bytes thus:</p> <pre><code>#ifdef ESCAPE_NULLS int i; for (i = 0; i &lt;= 6; i++) if (a[i] == 0) printf("\\0"); else printf("%c", a[i]); #else write(1, a, 6); #endif </code></pre> <p>But you have to know about the 6.</p> <p>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.</p> <pre><code>#include &lt;stdio.h&gt; typedef struct { int length; char *bytes; } bytearr; void my_printf(bytearr *arr) { #ifdef ESCAPE_NULLS int i; for (i = 0; i &lt;= arr-&gt;length; i++) if (arr-&gt;bytes[i] == 0) printf("\\0"); else printf("%c", arr-&gt;bytes[i]); #else write(1, arr-&gt;bytes, arr-&gt;length); #endif } void main(void) { bytearr foo = { 6, "\0hey\0\0" }; my_printf(&amp;foo); } </code></pre> <p>Graceless, but hopefully you get the idea.</p> <p><strong>Edit: 2011-05-31</strong></p> <p>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 <a href="http://linux.die.net/man/3/memcpy" rel="noreferrer"><code>memcpy</code></a>.</p> <pre><code>#include &lt;string.h&gt; char *a = "\0hey\0\0"; /* 6 */ char *b = "word\0up yo"; /* 10 */ char *c = "\0\0\0\0"; /* 4 */ void main(void) { char z[20]; char *zp = z; zp = memcpy(zp, a, 6); zp = memcpy(zp, b, 10); zp = memcpy(zp, c, 4); /* now z contains all 20 bytes, including 8 NULLs */ } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload