0

I am trying to reverse a string but when I run the code , the program crashes . What am I doing wrong? The program is supposed to show at first , the string without being reversed and then reversed.

P.S: If you haven't noticed I am totally new in C.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reverseString(char* str);
int main()
{
    char* str = "Hello World";
    printf(str);
    reverseString(str);
    return 0;
}
void reverseString(char* str)
{
    int i, j;
    char temp;
    i=j=temp=0;

    j=strlen(str)-1;
    for (i=0; i<j; i++, j--)
    {
        temp=str[i];
        str[i]=str[j];
        str[j]=temp;
    }
    printf(str);
}
fador
  • 23
  • 4
  • 3
    You are modifying a string literal. – ouah Mar 20 '15 at 23:26
  • possible duplicate of [How do you reverse a string in place in C or C++?](http://stackoverflow.com/questions/198199/how-do-you-reverse-a-string-in-place-in-c-or-c) – beresfordt Mar 20 '15 at 23:27
  • You may want to use strrev() function, however as already mentioned, you are trying to modify "Hello World" in place, but this is a string literal, meaning, it is in read-only memory and you will get an exception. You first need to copy it to a character array and modify the array. – DNT Mar 20 '15 at 23:29
  • so , if I copy it to an array and pass it to the function , it should work, right? – fador Mar 20 '15 at 23:31
  • 1
    Yes that would work. Or change `char* str = "Hello World";` to `char str[] = "Hello World";` At least then you're dealing with a mutable sequence of `char` rather than a read-only literal. – WhozCraig Mar 20 '15 at 23:35

1 Answers1

0

Reversing function is fine, the problem lies elsewhere.

char* str = "Hello World";

Here, str points to a string literal, that is immutable. It is placed in data segment of your program and modification of it's content will always result in crash.

Try this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reverseString(char* str);
int main()
{
    char str [256];
    strcpy_s(str, "Hello World");
    printf(str);
    reverseString(str);
    return 0;
}
void reverseString(char* str)
{
    int i, j;
    char temp;
    i=j=temp=0;

    j=strlen(str)-1;
    for (i=0; i<j; i++, j--)
    {
        temp=str[i];
        str[i]=str[j];
        str[j]=temp;
    }
    printf(str);
}

Another option is strrev() function.

JS1
  • 4,745
  • 1
  • 14
  • 19
Mateusz Grzejek
  • 11,698
  • 3
  • 32
  • 49