J
Johnathan Doe
Why is is necessary to write a function that allocates memory for, or
changes, a pointer to a char array using char** instead of char*?
E.g.
void modify_string( char** string )
{
if( string == NULL )
return;
if( *string != NULL )
free( *string );
*string = ( char * )calloc( n, sizeof( char ) );
strncpy( *string, "Whatever", n );
}
If this is written using the parameter char** string as char *string it
doesn't work (? or only if that function passes the string to some other
function which allocates and initialises the string?) Same with passing
in a pointer to a structure that needs to be allocated and filled in
with pointers to strings that also need allocating.
E.g.
void f( struct foo **f )
{
*f = malloc( sizeof( struct foo ) );
(*f)->string = ( char *)calloc( n, sizeof( char ) );
...
}
Does this have something to do with C parameters being passed by value?
E.g. you get a copy of a pointer and not the actual pointer, hence you
need a copy of a pointer to the actual pointer or somesuch?
Thanks,
Johnathan
changes, a pointer to a char array using char** instead of char*?
E.g.
void modify_string( char** string )
{
if( string == NULL )
return;
if( *string != NULL )
free( *string );
*string = ( char * )calloc( n, sizeof( char ) );
strncpy( *string, "Whatever", n );
}
If this is written using the parameter char** string as char *string it
doesn't work (? or only if that function passes the string to some other
function which allocates and initialises the string?) Same with passing
in a pointer to a structure that needs to be allocated and filled in
with pointers to strings that also need allocating.
E.g.
void f( struct foo **f )
{
*f = malloc( sizeof( struct foo ) );
(*f)->string = ( char *)calloc( n, sizeof( char ) );
...
}
Does this have something to do with C parameters being passed by value?
E.g. you get a copy of a pointer and not the actual pointer, hence you
need a copy of a pointer to the actual pointer or somesuch?
Thanks,
Johnathan