Simple modification of C strings using pointers

隐身守侯 提交于 2019-12-01 20:22:50

You are attempting to modify a string literal. String literals are not modifiable (i.e., they are read-only).

A program that attempts to modify a string literal exhibits undefined behavior: the program may be able to "successfully" modify the string literal, the program may crash (immediately or at a later time), a program may exhibit unusual and unexpected behavior, or anything else might happen. All bets are off when the behavior is undefined.

Your code declares original_string as a pointer to the string literal "ABC":

char* original_string = "ABC";

If you change this to:

char original_string[] = "ABC";

you should be good to go. This declares an array of char that is initialized with the contents of the string literal "ABC". The array is automatically given a size of four elements (at compile-time), because that is the size required to hold the string literal (including the null terminator).

Christian

The problem is that you can't modify the literal "ABC", which is read only.

Try char[] original_string = "ABC", which uses an array to hold the string that you can modify.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!