Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Maybe I'm just old and grumpy, but the other answers I've seen seem to miss the point completely.</p> <p>C does not do array assignments, period. You cannot assign one array to another array by a simple assignment, unlike some other languages (PL/1, for instance; Pascal and many of its descendants too - Ada, Modula, Oberon, etc.). Nor does C really have a string type. It only has arrays of characters, and you can't copy arrays of characters (any more than you can copy arrays of any other type) without using a loop or a function call. [String literals don't really count as a string type.]</p> <p>The only time arrays are copied is when the array is embedded in a structure and you do a structure assignment.</p> <p>In my copy of K&amp;R 2nd Edition, exercise 1-19 asks for a function <code>reverse(s)</code>; in my copy of K&amp;R 1st Edition, it was exercise 1-17 instead of 1-19, but the same question was asked.</p> <p>Since pointers have not been covered at this stage, the solution should use indexes instead of pointers. I believe that leads to:</p> <pre><code>#include &lt;string.h&gt; void reverse(char s[]) { int i = 0; int j = strlen(s) - 1; while (i &lt; j) { char c = s[i]; s[i++] = s[j]; s[j--] = c; } } #ifdef TEST #include &lt;stdio.h&gt; int main(void) { char buffer[256]; while (fgets(buffer, sizeof(buffer), stdin) != 0) { int len = strlen(buffer); if (len == 0) break; buffer[len-1] = '\0'; /* Zap newline */ printf("In: &lt;&lt;%s&gt;&gt;\n", buffer); reverse(buffer); printf("Out: &lt;&lt;%s&gt;&gt;\n", buffer); } return(0); } #endif /* TEST */ </code></pre> <p>Compile this with -DTEST to include the test program and without to have just the function <code>reverse()</code> defined.</p> <p>With the function signature given in the question, you avoid calling <code>strlen()</code> twice per line of input. Note the use of <code>fgets()</code> — even in test programs, it is a bad idea to use <code>gets()</code>. The downside of <code>fgets()</code> compared to <code>gets()</code> is that <code>fgets()</code> does not remove the trailing newline where <code>gets()</code> does. The upsides of <code>fgets()</code> are that you don't get array overflows and you can tell whether the program found a newline or whether it ran out of space (or data) before encountering a newline.</p>
 

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