Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to change char* value at any index?

Tags:

c++

arrays

char

As I know, if we declare char* in our program then it gives memory from read-only area, so we are not able to change a char at any position in the array.

char *ch = "sitaram";
ch[2] = 'y';

The above code will not run properly, as we are changing read-only memory.

One approach is we can declare our char array as

char ch[] = "sitaram";

and then we can change a value at an index.

Is there any way where I can change a char value at any index in a char*?

like image 231
sitaram chhimpa Avatar asked Sep 07 '25 00:09

sitaram chhimpa


1 Answers

Use the modern C++ approach for mutable string values

std::string str{"sitaram"};
str[2] = 'y';

String literals (i.e. values enclosed in "") are by default of type const char[n] (where n is the length of the string literal +1 for the null character) in C++ and because of that they are immutable, any attempt to modify them results in undefined behavior.

like image 154
Curious Avatar answered Sep 08 '25 22:09

Curious