I am implementing a function that acts like getline (..). Therefore my initial approach:
#include <cstdio>
#include <cstdlib>
#include <cstring>
void getstr( char*& str, unsigned len ) {
char c;
size_t i = 0;
while( true ) {
c = getchar();
if( '\n' == c || EOF == c ) {
*( str + i ) = '\0';
break;
}
*( str + i ) = c;
if( i == len - 1 ) {
len = len + len;
str = ( char* )realloc( str, len );
}
++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;
}
Then, I think I should switch to pure C instead of using half C / C ++. So I change char * & to char **: Pointer to a pointer version (crahsed)
#include <cstdio>
#include <cstdlib>
#include <cstring>
void getstr( char** str, unsigned len ) {
char c;
size_t i = 0;
while( true ) {
c = getchar();
if( '\n' == c || EOF == c ) {
*( *str + i ) = '\0';
break;
}
*( *str + i ) = c;
if( i == len - 1 ) {
len = len + len;
*str = ( char* )realloc( str, len );
}
++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;
}
But this version crashed, (violation of access rights). I tried to run the debugger, but I could not find where it crashed. I am running Visual Studio 2010, so could you guys show me how to fix this?
Another weird thing I came across is that if I leave "&" out, it only works with Visual Studio, but not with g ++. it
void getstr( char* str, unsigned len )
, , , , . , **, * & . , Visual Studio, ?