for example:
char stringer[]="hello";
stringer[2]='A';
The above works to change 'l'
to 'A'
. But if I do the following:
char *stringer="hello";
stringer[2]='A';
This doesn't work, is there a reason for this?
for example:
char stringer[]="hello";
stringer[2]='A';
The above works to change 'l'
to 'A'
. But if I do the following:
char *stringer="hello";
stringer[2]='A';
This doesn't work, is there a reason for this?
As answered by Some programmer dude in comments:
Literal strings are really non-modifiable arrays of characters. With char *stringer="hello";
you make stringer
point to the first character of such an array. Attempting to modify its contents leads to undefined behavior.
That's why you should always use const char *
when pointing to literal strings.
Strings can be modified when using pointer, if the pointer is pointing to something you're allowed to modify. For example
char stringer[] = "hello";
char *pointer = stringer;
pointer[2] = 'A';