Search

11/01/2006

pointer pointer pointer


void GetMemory( char *p ){
p = (char *) malloc( 100 );
}

void Test( void ) {
char *str = NULL;
GetMemory( str );
strcpy( str, "hello world" );
printf( str );
}

在GetMemory中, p是local variable, 所以GetMemory( str )後,str仍然是NULL.
應改為

void GetMemory( char **p ){
p = (char *) malloc( 100 );
}

void Test( void ) {
char *str = NULL;
GetMemory( &str );
strcpy( str, "hello world" );
printf( str );
}

沒有留言: