0
char *str = "string" ;
char *end = str;
while(*(end+1) != '\0') {
    end++;
}

while(str < end) {
    char temp = *str;
    *str = *end;
    *end = temp;
    str++;
    end--;
}`

EDIT: Are both these*str = *end, *str++ = *end invalid?

The above code gives error at that line.

Aren't str and end pointing to a read only part in memory whether it be post increment?

rldl
  • 73
  • 1
  • 9
  • They're both invalid. Why do you think they aren't? – melpomene Oct 02 '15 at 22:03
  • The first line should be `char str[] = "string";`. That way the string is in writable memory, and you can change it. Technically, your code has undefined behavior, which means that it may or may not work, depending on whether it does or not. – user3386109 Oct 02 '15 at 22:31
  • MY BAD. I meant *str++ = *end; – rldl Oct 02 '15 at 22:38

1 Answers1

1
char *str = "string" ;

Is a string literal placed in a read-only data section.

In this line:

*str = *end;

is trying to modify the string, you would probably get a segfault..

Same for *str++ = *end, both are invalid.

To make this code work, change

char *str = "string";

to

char str[] = "string";

But note that you can not use *str++ because array names are constant (not modifiable lvalue)

Community
  • 1
  • 1
David Ranieri
  • 39,972
  • 7
  • 52
  • 94