 <p>First of all, I will assume that this is homework and you must not use <code>std::string</code>. If you can use <code>std::string</code>, forget about everything and refrain from using dynamically allocated C-style strings!</p> <hr> <p>Here we go. If you want to replace <em>one</em> character (a space) with <em>two</em> characters (two stars), then your output string becomes <strong>larger</strong>.</p> <pre><code>"hello there, world!" = 19 characters "hello**there,**world!" = 21 characters </code></pre> <p>I doubt that overwriting the character following each space with a star conforms to the requirements of this exercise:</p> <pre><code>"hello**here,**orld!" = 19 characters, but seems to be wrong </code></pre> <p>You have space for 49 characters, but what if you enter, say, a string with 45 non-spaces and 5 spaces? The result would consist of 55 characters. More generally speaking: <strong>Who says the resulting string will fit in the old array?</strong></p> <p>The easiest way to overcome this problem and arrive at a satisfactory solution is to first <em>count</em> the number of spaces, then <em>allocate a new string</em>, then <em>copy</em> the characters.</p> <p>Here is an example. I left your original way of receiving user input, and a few other problems with the code, intact, even though it could use a few further improvements. This is <em>not</em> C++ code you would use in production! I also used <code>malloc</code> and <code>free</code> to conform to the general C-style of your code (in fact, this may really be a C exercise!). Take it strictly as a learning exercise:</p> <pre><code>#include&lt;iostream&gt; #include&lt;cstdio&gt; #include&lt;cstring&gt; #include&lt;cstdlib&gt; using namespace std; int new_size(char str[]); char* convert(char str[], int new_size); int main() { char string[50]; cout&lt;&lt;"Enter a string "&lt;&lt;endl; gets(string); int new_size_with_stars = new_size(string); char* new_string = convert(string, new_size_with_stars); printf("result: %s\n", new_string); free(new_string); return 0; } int new_size(char str[]) { int result = 0; for (int i = 0; str[i] != '\0'; ++i) { if (str[i] == ' ') { ++result; } ++result; } return result; } char* convert(char str[], int new_size) { char* new_str = (char*) malloc(new_size + 1); for(int old_str_index = 0, new_str_index = 0; str[old_str_index] != '\0'; ++old_str_index, ++new_str_index) { if (str[old_str_index]==' ') { new_str[new_str_index] = '*'; new_str[new_str_index + 1] = '*'; ++new_str_index; } else { new_str[new_str_index] = str[old_str_index]; } } new_str[new_size] = '\0'; return new_str; } </code></pre>