segmentation fault (core dumped) when changing string characters

前端 未结 2 490
予麋鹿
予麋鹿 2021-01-24 13:24

Why changing string characters causes segmentation fault(core dumped):

char *str = \"string\";
str[0] = \'S\'; //segmentation fault(core dumped) 
2条回答
  •  逝去的感伤
    2021-01-24 14:27

    char *str = "string"; points to a read-only part of memory and because of that the string can't be changed.

    You need to declare an array instead of a pointer which points to an array if you want to change the array like this

    char str[] = "string";
    

提交回复
热议问题