Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The code below ensures that the strings can't overflow by making the output string as long as the two input strings, and using <code>fgets()</code> to ensure that there is no overflow of the input strings. One alternative design would do dynamic memory allocation (<code>malloc()</code> et al), at the cost of the calling code having to <code>free()</code> the allocated space. Another design would pass the length of the output buffer to the function so that it could ensure no overflow occurs.</p> <p>The test program doesn't emit prompts: it would not be hard to add a function to do so.</p> <h3>Code</h3> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; void interleave_strings(const char *s1, const char *s2, char *output) { while (*s1 != '\0' &amp;&amp; *s2 != '\0') { *output++ = *s1++; *output++ = *s2++; } while (*s1 != '\0') *output++ = *s1++; while (*s2 != '\0') *output++ = *s2++; *output = '\0'; } int main(void) { char line1[100]; char line2[100]; char output[200]; if (fgets(line1, sizeof(line1), stdin) != 0 &amp;&amp; fgets(line2, sizeof(line2), stdin) != 0) { char *end1 = line1 + strlen(line1) - 1; char *end2 = line2 + strlen(line2) - 1; if (*end1 == '\n') *end1 = '\0'; if (*end2 == '\n') *end2 = '\0'; interleave_strings(line1, line2, output); printf("In1: &lt;&lt;%s&gt;&gt;\n", line1); printf("In2: &lt;&lt;%s&gt;&gt;\n", line2); printf("Out: &lt;&lt;%s&gt;&gt;\n", output); } } </code></pre> <h3>Example output</h3> <pre><code>$ ./interleave abcdefgh 1234 In1: &lt;&lt;abcdefgh&gt;&gt; In2: &lt;&lt;1234&gt;&gt; Out: &lt;&lt;a1b2c3d4efgh&gt;&gt; $ </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

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