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

}
2
  • 1
    you can't modify a string constant, use char string[] = "stack overflow" instead Commented Mar 12, 2013 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? Commented Mar 12, 2013 at 23:57

1 Answer 1

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";
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.