Function to reverse string in C

后端 未结 4 1149
终归单人心
终归单人心 2021-01-28 08:03

I wrote this function to reverse a string in C, but when switching characters in the string the program crashes. I have no idea what\'s causing it, so any help would be apprecia

相关标签:
4条回答
  • 2021-01-28 08:33

    "Example" is a string literal, which usually means you cannot change it.

    Please try this:

    char str[] = "Example";
    reverse(str);
    
    0 讨论(0)
  • 2021-01-28 08:41

    You need to take character pointer as a parameter in your function:

    Void reverse (char *ptr)
    {
        // ...
    }
    

    And perform operation on pointer.

    0 讨论(0)
  • 2021-01-28 08:54

    This should work:

    #include<string.h>
    
    int main()
    {
      char str[100], temp = 0;
      int i = 0, j = 0;
    
      printf("nEnter the string :");
      gets(str);
    
      i = 0;
      j = strlen(str)-1;
    
      while(i<j)
      {
        temp=str[i];
        str[i]=str[j];
        str[j]=temp;
        i++;
        j--;
      }
    
      printf("nReverse string is :%s",str);
    
      return(0);
    }
    
    0 讨论(0)
  • 2021-01-28 08:55

    read this for more information What is the difference between char s[] and char *s?

    Another link https://stackoverflow.com/questions/22057622/whats-the-difference-structurally-between-char-and-char-string#22057685

    this should fix it.

    main()
    {    
    char array[] = "Example";
    reverse(array); 
    }
    

    when you do reverse("Example") this is the same as

    char *string = "Example";
    reverse(string) //wont work
    

    The links should clarify your doubts from here.

    0 讨论(0)
提交回复
热议问题