printf string, variable length item

前端 未结 2 1645
独厮守ぢ
独厮守ぢ 2020-11-28 07:11
#define SIZE 9
int number=5;
char letters[SIZE]; /* this wont be null-terminated */
... 

char fmt_string[20];
sprintf(fmt_string, \"%%d %%%ds\", SIZE);
/* fmt_strin         


        
2条回答
  •  Happy的楠姐
    2020-11-28 08:09

    A somewhat unknown function is asprintf. The first parameter is a **char. This function will malloc space for the string so you don't have to do the bookkeeping. Remember to free the string when done.

    char *fmt_string;
    
    asprintf(&fmt_string, "%%d %%%ds", SIZE);
    printf(fmt_string, number, letters);
    free(fmt_string);
    

    is an example of use.

提交回复
热议问题