Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing characters in a char*

Tags:

c++

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: aaaaa

like image 457
okay14 Avatar asked Mar 11 '23 12:03

okay14


1 Answers

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";
like image 124
Some programmer dude Avatar answered Mar 20 '23 13:03

Some programmer dude