rldl
rldl

Reputation: 73

Confusion with Pointers Increment

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?

Upvotes: 0

Views: 86

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

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)

Upvotes: 1

Related Questions