Function to reverse string in C

和自甴很熟 提交于 2019-12-20 05:40:36

问题


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 appreciated.

void reverse(char s[])
{
    char c;
    int i;
    int j;

    for (i = 0, j = (strlen(s) - 1); i < j; i++, j--)
    {
        c = s[i];
        s[i] = s[j]; //An error occurs here
        s[j] = c;
    }

    printf("%s", s);
}

main()
{
    reverse("Example");
}

回答1:


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.




回答2:


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

Please try this:

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



回答3:


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);
}



回答4:


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

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

And perform operation on pointer.



来源:https://stackoverflow.com/questions/22069759/function-to-reverse-string-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!