String Compression (C++)
<p>The problem is counting the number of times a character appears and returning the compressed string. For example, <strong>"aaabbcc"</strong> would return <strong>"a3b2c2".</strong> </p>

<p>I have the code (not mine), and am struggling to understand some of the logic behind it. The full code is: </p>

<pre><code>#include &lt;iostream&gt;
using namespace std;

int main() {
    char input[] = "aaabbcc";
    char* read = input;
    char* write = input;

    char curr = input[0];
    int count = 0;

    while ( *read != '\0' ) {
        if ( *read == curr ) {
            count++;
        }
        else {
            *write++ = curr;
            *write++ = count + '0';
            count = 1;
        }
        curr = *read;
        read++;
    }

    *write++ = curr;
    *write++ = count + '0';
    *write = '\0';

    cout &lt;&lt; input &lt;&lt; endl;
    return 0;
}
</code></pre>

<p>My understanding so far is that the read pointer points to <strong>a</strong>, and the write pointer points to <strong>a</strong> as well (first character in the string). The character <code>curr</code> is then set to <strong>a</strong> as well. The <code>while</code> loops starts, saying that until the end of the string is reached (the null character), set the character of <code>curr</code> to <code>read</code>. </p>

<p>What I am confused about is starting from this line <code>*write++ = curr;</code>. <code>write</code> is currently pointing to the first character of the string. Is this saying to dereference, and then increment the position? Given an input of <strong>"aaabbcc"</strong>, this would mean that now <code>write</code> is pointing to the second <strong>a</strong>? But then this is assigned the value of <code>curr</code>? </p>

<p>I guess my other question is how does it go from <strong>"aaa"</strong> to just <strong>"a3"</strong>?</p>

<p>Thanks in advance for any answers. </p>