How to pass pointer and pointer to a function?
<p>I implement a function that acts like getline( .. ). So my initial approach is:</p>

<pre><code>#include &lt;cstdio&gt;
#include &lt;cstdlib&gt;
#include &lt;cstring&gt;

void getstr( char*&amp; str, unsigned len ) {
    char c;
    size_t i = 0;
    while( true ) {
        c = getchar(); // get a character from keyboard
        if( '\n' == c || EOF == c ) { // if encountering 'enter' or 'eof'
            *( str + i ) = '\0'; // put the null terminate
            break; // end while
        }
        *( str + i ) = c;
        if( i == len - 1 ) { // buffer full 
            len = len + len; // double the len 
            str = ( char* )realloc( str, len ); // reallocate memory
        }
        ++i;
    }
}

int main() {
    const unsigned DEFAULT_SIZE = 4;
    char* str = ( char* )malloc( DEFAULT_SIZE * sizeof( char ) );
    getstr( str, DEFAULT_SIZE );
    printf( str );
    free( str );
    return 0;
}
</code></pre>

<p>Then, I think I should switch to pure C instead of using half C/C++. So I change char*&amp; to char**:
Pointer to Pointer version ( crahsed )</p>

<pre><code>#include &lt;cstdio&gt;
#include &lt;cstdlib&gt;
#include &lt;cstring&gt;

void getstr( char** str, unsigned len ) {
    char c;
    size_t i = 0;
    while( true ) {
        c = getchar(); // get a character from keyboard
        if( '\n' == c || EOF == c ) { // if encountering 'enter' or 'eof'
            *( *str + i ) = '\0'; // put the null terminate
            break; // done input end while
        }
        *( *str + i ) = c;
        if( i == len - 1 ) { // buffer full 
            len = len + len; // double the len 
            *str = ( char* )realloc( str, len ); // reallocate memory
        }
        ++i;
    }
}

int main() {
    const unsigned DEFAULT_SIZE = 4;
    char* str = ( char* )malloc( DEFAULT_SIZE * sizeof( char ) );
    getstr( &amp;str, DEFAULT_SIZE );
    printf( str );
    free( str );
    return 0;
} 
</code></pre>

<p>But this version crashed, ( access violation ). I tried run the debugger, but I could not find where it crashed. I'm running Visual Studio 2010 so could you guys show me how to fix it?</p>

<p>Another weird thing I've encountered is that, if I leave the "&amp;" out, it only works with Visual Studio, but not g++. That is</p>

<pre><code>void getstr( char* str, unsigned len ) 
</code></pre>

<p>From my understanding, whenever we use pointer to allocate or deallocate a block of memory, we actually modify where that pointer are pointing to. So I think we have to use either ** or *&amp; to modify the pointer. However, because it run correctly in Visual Studio, is it just luck or it should be ok either way?</p>

<p>Best Regards,<br>
Chan </p>
