2

so I was playing with pointers because I didn't know what else to do and usually, I imagine what's going on under the hood after each instruction. But I recently came against an error that I don't really understand.

char *str = "test";
printf("%c", ++*str);

Output :

zsh: bus error

Expected output was a 'u' because as far as I know, it first dereference the first address of the variable 'str' wich is a 't' than increment it right ? Or am I missing something ?

Changing the code like so is not giving me any error but why ?

printf("%c", *++str);

Thank you !

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
Liwinux
  • 87
  • 6

1 Answers1

3

You cannot modify the data in a string literal. What you expect will work if you do:

char buf[] = "test"; 
char *str = buf;
putchar(++*str);

because the content of buf is writeable.

William Pursell
  • 204,365
  • 48
  • 270
  • 300