Write code sample for string reversal program in c by using for loop and using only one buffer

Showing Answers 1 - 7 of 7 Answers

shiva

  • Sep 27th, 2011
 

We can use directly strrev ()

Code
  1.  

  2. #include <string.h>

  3. #include <stdio.h>

  4.  

  5. int main(void)

  6. {

  7.    char *forward = "string";

  8.  

  9.    printf("Before strrev(): %s

  10. ", forward);

  11.    strrev(forward);

  12.    printf("After strrev():  %s

  13. ", forward);

  14.    return 0;

  15. }

  16.  

  Was this answer useful?  Yes

Below is a simple, straightforward, maybe not the fastest method for reversing a string in place.

Why not start j at strlen(str) - 1? If the string is empty, strlen will return 0, and since size_t is an unsigned type, 0 - 1 will result in some huge value, inevitably leading to a segmentation fault when we try to write to that location.

Code
  1. #include <stdio.h>

  2. #include <string.h>

  3. #include <assert.h>

  4.  

  5. /**

  6.  * Reverse a string in place.  str must point to

  7.  * a writable buffer (i.e., not a string constant)

  8.  */

  9. void reverse(char *str)

  10. {

  11.   size_t i,j;

  12.  

  13.   assert(str != NULL);

  14.  

  15.   for(i = 0, j = strlen(str); i < j; i++)

  16.   {

  17.     char tmp = str[--j];

  18.     str[j] = str[i];

  19.     str[i] = tmp;

  20.   }

  21. }

  22.  

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions