Note that there are some explanatory texts on larger screens.

plurals
  1. POHelp with reversing a string in C
    primarykey
    data
    text
    <p>I am trying to reverse a character string in C</p> <p>Here is what I have</p> <pre><code>void reverse(char str[]) { int i = 0; int length; // Get string length for (i = 0; str[i] != '\0' ; ++i) { length = i; } char reversed[1000]; int j; j = 0; // Reverse it for (j = 0; j &lt; length ; ++j) { reversed[j] = str[length - j]; } } </code></pre> <p>I know that <code>reversed</code> contains the string reversed, but I'm not sure how to modify the original <code>str</code> without throwing away data I need.</p> <p>I also don't know how to set <code>str</code>to <code>reversed</code> without looping <em>again</em>.</p> <p>Would it be acceptable to do another...</p> <pre><code> int m; m = 0; for (m = 0; m &lt; length ; ++m) { str[j] = reversed[j]; } </code></pre> <p>Usually I'd say this many loops smells, but I'm also still quite unfamiliar with the language so I'm not sure...</p> <h2>Update</h2> <p>Thanks for all the answers guys, and I appreciate the edits too!</p> <p>I ended up going with <a href="http://codepad.org/tQmMFzFq" rel="nofollow noreferrer">this</a>...</p> <pre><code>int main() { char str[] = "Reverse me!"; int length; for (length = 0; str[length] != '\0'; length++) { } printf("length =&gt; %d chars\n", length); int j, k; char c; for (j = 0, k = length - 1; j &lt; k; j++, k--) { c = str[k]; str[k] = str[j]; str[j] = c; } printf("reversed =&gt; %s\n", str); return 0; } </code></pre> <p>Some things I now know...</p> <ul> <li>There is a <code>strlen()</code> like in PHP. However, it has not been discussed in the book yet, plus I need to get familiar with null terminated strings.</li> <li>A <code>for</code> loop can assign and do multiple things that are comma separated. I never knew this! </li> </ul> <p>So asking was worthwhile :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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