okay14 okay14 - 2 months ago 5
C++ Question

Replacing characters in a char*

How would one go to replace characters in a char*?

For example:

int main() {
char* hello = "hello";
int i;

for (i = 0; i < 5; i++) {
hello[i] = 'a';
cout << hello;

No output at all. Just pauses on me and says that the program isn't responding.

Expected output:


The problem here is that you have a pointer to a string literal, and string literals in C++ are constant arrays of characters. Attempting to modify constant data leads to undefined behavior.

You can solve this by making hello an array:

char hello[] = "hello";