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*
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With