-2

I am trying to reverse a string. I take two pointers , one pointing to the start of the string and other at the end of the string . And then I swap the values of the pointers.

int main()
{

    char *string = "stack overflow";
    int len = strlen(string);
    char *end;
    char tmp; //temporary variable to swap values

    //pointer pointing at the end of the string
    end = string+len-1;

    printf(" value of start and end %c %c", *string , *end); //correct values printed
    while(string<end)
        {

                tmp = *string;
                *string = *end; //segmentation fault
                *end = tmp;
                *string++;
                *end--;


        }


    return 0;

}
user968000
  • 1,765
  • 3
  • 22
  • 31
  • 1
    you can't modify a string constant, use `char string[] = "stack overflow"` instead – Stephen Lin Mar 12 '13 at 23:56
  • 2
    You are not swapping pointer values. You are swapping values *pointed by* those pointers. Anyway, this has been asked hundreds of times already [Why is this C code causing a segmentation fault?](http://stackoverflow.com/questions/1614723/why-is-this-c-code-causing-a-segmentation-fault) – AnT stands with Russia Mar 12 '13 at 23:57

1 Answers1

5
char *string = "stack overflow";

This creates a read-only string literal. Modifying it is undefined behavior. Use an array instead:

char string[] = "stack overflow";