0

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");
}
user3277234
  • 55
  • 3
  • 9
  • 4
    you can't change string literal. Use char array instead – Andrey Chernukha Feb 27 '14 at 13:21
  • You should create a new string, and return (or print) that one – Mathias711 Feb 27 '14 at 13:21
  • 1
    @user3277234 Just so you know, in functions, arrays are actually pointers (that is, you have `char *s`, not `char s[]`). Changing a single character in a char pointer is undefined behavior. So please follow @Mathias711's advice and create a new string. – Diti Feb 27 '14 at 13:23
  • 2
    @Diti It is perfectly valid to modify characters, single or multiple. The real culprit is the *string literal*, `s` points to. – Olaf Dietsche Feb 27 '14 at 13:36

4 Answers4

3

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.

Community
  • 1
  • 1
tesseract
  • 891
  • 1
  • 7
  • 16
1

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

Please try this:

char str[] = "Example";
reverse(str);
Lee Duhem
  • 14,695
  • 3
  • 29
  • 47
0

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

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

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

And perform operation on pointer.

Leopold Joy
  • 4,524
  • 4
  • 28
  • 37