0

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?

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
bugger
  • 137
  • 5
  • 4
    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. This should have been taught by any decent book, tutorial or class. – Some programmer dude Oct 15 '22 at 07:23
  • 1
    Also note that you *can* modify strings 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';` is perfectly valid and fine. – Some programmer dude Oct 15 '22 at 07:26

1 Answers1

0

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';
kgkmeekg
  • 524
  • 2
  • 8
  • 17