Modify the content of char* str

I'm trying to reverse the string via void function, but segmentation fault occurs for "str" it's stored read-only memory (as I known from searching existing thread in the forum).

I tried to use strcpy(copy, str) in "reverse" function but it's just reversing the newly created char array "copy" which cannot be returned to main function. I don't want to use printf("%s", copy) in the reverse function to print the reversed string.

Is there anyway to reverse str

  • Without changing it to char str[] = "Hello"
  • Without changing the code in main() function
  • Keep the function type of reverse() as void ?
  • void reverse(char* str)
    {
      int l = strlen(str);
      char temp;
      int j = length - 1;
    
      for (int i = 0; i < j; ++i)
      {
         temp = str[i];
         str[i] = str[j];
         str[j] = temp;
         --j;
      }
    }
    
    int main(int argc, char* argv[])
    {
       char* str = "Hello";
       reverse(str);
       printf("%sn", str);
       return 0;
    }
    

    The problem is you cannot modify string literals.

    Try like this:

    char str[] = "Hello";
    reverse(str);
    

    above, str is no longer a string literal, it's an array initialized to {'H', 'e', 'l', 'l', 'o', ''} , so you can modify it's contents if you want.

    Or you can use malloc()

    char *str = malloc(6);
    if (str != NULL)
     {
        strcpy(str, "Hello");
        reverse(str);
        fprintf(stdout, "%sn", str);
        /* And never forget to `free' */ 
        free(str);
     }
    

    When defining string literals use const to protect it from being modified, at least from accidentally doing so.

    There is no way to satisfy these requirements

  • Without changing it to char str[] = "Hello"

    Because you cannot modify string literals

  • Without changing the code in main() function

    Because that would require the program to modify a string literal and YOU CAN'T

  • The third requirement, does not impose any problem at all.


    everytime you use a pointer that you have to use a malloc() in C or new() in C++ which could probably be the issue. but you can always cast de-reference anything to its address back to a pointer like i did below

    DEMO: http://ideone.com/LnOtDL

    #include <string.h>
    
    void reverse(char* str)
    {
      int length = strlen(str);
      char temp;
      int j = length - 1;
    
      for (int i = 0; i < j; ++i)
      {
         temp = str[i];
         str[i] = str[j];
         str[j] = temp;
         --j;
      }
    }
    
    int main(int argc, char* argv[])
    {
       char str[] = "Hello";
       reverse(&str[0]);
       printf("%sn", str);
       return 0;
    }
    
    链接地址: http://www.djcxy.com/p/72152.html

    上一篇: C.传递要修改的指针导致段错误

    下一篇: 修改char * str的内容