-2

Possible Duplicate:
How to reverse a string in place in c using pointers?

I was trying to reverse a string using C. A segmentation fault occurs. Any idea why?

Here's my code:

    #include <stdio.h>
    #include <string.h>

    int main(void)
    {
    char *str1 = "abbd";
    char *str2;


    str2 = str2 + strlen(str1)-1;

    while(*str1 != '\0')
    *(str2--) = *(str1++);


    printf("%s", str2);

     return 0;
    }
2
  • Even if you figure out the segmentation fault, it's not going to change the string. Can you figure out why? Commented Mar 31, 2012 at 1:15
  • Even if you fix the bug everybody's pointed out to you, it's impossible to modify your string in place because that string is non-modifiable. You cannot modify string literals. Commented Mar 31, 2012 at 1:31

4 Answers 4

0

Nothing's properly allocated (allocate the proper length at declaration or malloc it) and you don't really move through the strings and check for the end of your condition as fitted (try str[i]). You have awaken the kraken.

Sign up to request clarification or add additional context in comments.

Comments

0

Looks like you didn't allocate any space for str2, just made the pointer.

Comments

0
char *str2;
str2 = str2 + strlen(str1)-1;

You declared a pointer str2, but initialize its value to garbage. (str2 + ...)

Are you trying to do an in-place modification? That won't work for this code, the char *foo="bar"; format places the "bar" in a write-protected memory space on platforms that support it.

Are you trying to do an out-of-place modification? If so, you forgot to allocate that space.

Comments

0

You're not allocating memory for str2.

str2 = (char *)malloc(sizeof(char) * (strlen(str1) + 1));

I haven't tried it, but it seems like you're going to want to set str2 = str2 + strlen(str1), otherwise I think you'll run off the "front" of your str2 buffer as well.

I would recommend treating your strings as arrays, and let the compiler do the pointer arithmetic for you.

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.