okay14 okay14 - 1 year ago 87
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:

Answer Source

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";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download