When writing code, you often need to specify a string based on the parameter. Every time you call vsprintf, malloc is annoying. The following is
The interface that implements this function.
/***************************************************************************** * Copyright : All Rights Reserved. * * Date : 2012-09-05 23:48:48 * Author/Corporation : Dengzhaoqun * Email : dengzhaoqun@163.com *****************************************************************************/#include <stdio.h>#include <stdlib.h>#include <string.h>#include <stdarg.h>char *xm_vsprintf_ex(int len, char *fmt, ... );int main(int argc, char *argv[]){char *ptr;ptr = xm_vsprintf_ex(100, "%s-%s-%s", "lias", "dzq", "lvo");printf("%s\n", ptr);free(ptr);return 0;}char *xm_vsprintf_ex(int len, char *fmt, ... ){va_list ap;char *ptr;ptr = (char *)malloc(len * sizeof(char));if(ptr == NULL){fprintf(stderr, "malloc failed\n");return NULL;}memset(ptr, 0, len);va_start(ap, fmt);vsprintf(ptr, fmt, ap);va_end(ap);ptr[len-1] = '\0';return ptr;}
It is quite easy to use.