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!