Friday, 15 January 2010

Converting the output of a void method to String in C -



Converting the output of a void method to String in C -

i have written void function takes unsigned int. phone call in main function. want output string can include in printf statement formatting reasons. since i'm calling void function, can't tell printf string (%s) or int (%d). how can take output called void function in main , turn kind of string or integer?

a function declared e.g. void foo(int); has no result. cannot convert inexistent result integer or string.

notice c not have stricto sensu string datatype. utilize pointer memory zones made of char, convention zero-terminate strings.

perhaps want output (done using printf, fprintf, fputs, , other stdio(3) standard library functions) of function string. on linux (and gnu libc) systems, utilize open_memstream(3)

do not confuse output of function result!

so suppose have written outputing function e.g.

void show_x(file*out, int x) { fprintf(out, "x=%d\n", x); }

then string ptrbuf (on linux) using:

char*ptrbuf=null; size_t sizbuf=0; file* outmem = open_memstream(&ptrbuf, &sizbuf); if (!outmem) { perror("open_memstream"); exit(exit_failure); }; show_x(outmem, 42); fflush(outmem); printf ("now ptrbuf %s\n", ptrbuf); fclose(outmem); // later should free `malloc`-ed `ptrbuf` free (ptrbuf), ptrbuf=null; sizbuf=0;

c string int

No comments:

Post a Comment