我实现了一个像getline(..)一样的函数.所以我最初的方法是:
#include <cstdio>
#include <cstdlib>
#include <cstring>
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; // 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;
}
Run Code Online (Sandbox Code Playgroud)
然后,我想我应该切换到纯C而不是使用半个C/C++.所以我将char*改为char**:Pointer to 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(); // 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( &str, DEFAULT_SIZE );
printf( str );
free( str );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是这个版本崩溃了,(访问违规).我试过运行调试器,但我找不到它崩溃的地方.我正在运行Visual Studio 2010所以你们能告诉我如何修复它吗?
我遇到的另一个奇怪的事情是,如果我离开"&",它只适用于Visual Studio,但不适用于g ++.那是
void getstr( char* str, unsigned len )
Run Code Online (Sandbox Code Playgroud)
根据我的理解,每当我们使用指针来分配或释放一块内存时,我们实际上会修改指针所指向的位置.所以我认为我们必须使用**或*&来修改指针.但是,因为它在Visual Studio中运行正常,它只是运气还是应该没问题?