yp*********@indiatimes.com wrote:
Hello All,
To use sprintf function we have to first create a char * and assign
some memory to it or we have to fixed memory sized array.
eg.
char str[512];//or it can be
//char * str =(char *)malloc(512);
Don't cast the result of malloc. Make sure you do #include <stdlib.h>
int d=100;
float f=2.22;
sprintf(str,"Test of sprintf %d %f"),d,f);
free(str);
if there any library function which can avoid allocating memory to str.
i.e i can write
char * str = NULL;
and directly pass str to that printf like function and the function
will internally handle the allocation of memory and releasing it.
Sure, you can write a function like that. To do it properly, you'll need
to use vsnprintf inside your function, but vsnprintf was added by C99
and has not yet appeared in all implementations of the C standard library.
so i can write the code like
eg.
char * str = NULL;
testprintf(str,"Test of sprintf %d%f"),d,f);
This exact form is not possible, since testprintf must modify the value
of the pointer str, but it receives only a copy of the value, and has no
way to return the new value to the caller. You need to pass a pointer to
str.
testprintf(&str,"Test of sprintf %d%f", d, f);
The prototype of the function should be
int testprintf(char **pstr, const char *format, ...);
Here's a possible implementation:
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
int testprintf(char **pstr, const char *format, ...)
{
va_list ap1, ap2;
va_start(ap1, format);
va_copy(ap2, ap1);
int n = vsnprintf(NULL, 0, format, ap1);
*pstr = malloc(n);
if(*pstr)
{
vsnprintf(*pstr, n, format, ap2);
}
va_end(ap1);
va_end(ap2);
return n;
}
int main(void)
{
char *str;
testprintf(&str, "test sprintf %d %f", 42, 42.0);
printf("%s\n", str);
free(str);
return 0;
}
--
Simon.