Saturday, 15 May 2010

function - C Pass by reference string -



function - C Pass by reference string -

i want modify string within function. code pretty easy:

#include <stdio.h> void dosomething ( char **string ) { sprintf(string,"some string"); } int main ( void ) { char *origstring = null; dosomething ( &origstring ); printf ( "%s\n", origstring ); homecoming 0; }

but code doesn't work. appreciate explanation more solution, solution welcome.

i need utilize sprintf function, because thought add together other strings %s.

thanks!

solved!

#include <stdio.h> void dosomething ( char **string ) { *string = malloc(strlen("some string") + 1); sprintf(*string,"some string"); } int main ( void ) { char *origstring = null; dosomething ( &origstring ); printf ( "%s\n", origstring ); free(origstring); // malloced in dosomething homecoming 0; }

sprintf takes char* first argument, not char**, should sprintf(*string,"some string");. *string null @ point, still not work.

if want memory string allocated dosomething function, need allocate memory in function. sprintf not allocate memory you. before you'd phone call sprintf, you'd need allocate memory using malloc , create *string point memory. should aware users of function needs free memory 1 time they're done it.

c function reference char c-strings

No comments:

Post a Comment