This is a newbie question. To create a formatted C string, I use printf, like:
int n = 10;
printf("My number is %i", 10);
But, how about:
int n = 10
char *msg = "My number is %i", 10;
printf(msg);
How can I store the resulting formatted string in a variable? I want “My number is 10”.
You want to use
snprintf():Do not use
sprintf(); it is similar tosnprintfbut does not perform any buffer size checking so it is considered a security hole – of course you might always allocate enough memory but you might forget to it at some point and thus open a huge security hole.If you want the function to allocate memory for you, you can use
asprintf()instead: