Search code examples
cstringpointerscygwin

reverse c style string


I know this question has been asked many times but I am completely stuck.

EDIT: This question is different from previous questions because the problem was not with the code for the reverse function, but rather what types of values can be passed to the reverse function (ie. array vs pointer) .. see answers below for more info.

I am simply trying to reverse a c style string. I have taken copied and pasted the code to do so directly from Cracking the Coding Interview. (see below)

void reverse(char *str) {
    char * end = str;
    char tmp;
    if (str) {
        while (*end) {
            ++end;
        }
        --end;
        while (str < end) {
            tmp = *str;
            *str++ = *end;
            *end-- = tmp;
        }
    }
}

This does not work for me. I am very new to C so perhaps I am compiling the code wrong. My main function looks like:

int main(int argc, char *argv[])
{   
    char *string = "foobar";
    reverse(string);
    printf("%s\n", string);

    return 0;
}

I am using Cygwin with Windows 8.1 and on the command line I am running:

gcc ex1.c -Wall -o exe1
./exe1

Everytime I get a pop up from windows saying "exe1.exe has stopped working". I tried putting a print statement in the while loop to try debug and see what is going on. It reaches the while loop once before the windows pop up appears.

EDIT: After reading the comments I have also tried changing the code in main to :

char string[] = "foobar"; 
reverse(string);

When I do this my program just hangs.

What am I doing wrong?

Thanks!


Solution

  • The problem with your code is pertaining to this part char *string = "foobar"; Here "foobar" is stored in a memory location and string holds the first location of "foobar" so basically now string behaves as a const so you cannot change its contents.

    You could do this instead char string[] = "foobar";.

    EDIT: as @jonathan-leffler mentioned, I forgot to mention the memory locations.

    char *string = "foobar";
    Is stored on the Data Segment which is given memory during compile time and attempts to modify this during runtime will give you a Seg Fault.

    whereas,
    char string[] = "foobar";
    Is stored on the stack and can be modified.

    EDIT2: Read the comments below @jonathan-leffler has more to add