What I’m trying to do is make a new char* using a syntax similar to printf:
char* myNewString = XXXXprintf("My string says %s", myFirstString);
Is this doable without printing to an output stream?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You’re looking for the
sprintforsnprintffunction.Note that
sprintfdoesn’t return a pointer to a newly allocated string; you have to allocate the string yourself, and make sure it’s big enough:Unless you can be certain that the target is big enough, you should use
snprintf, which limits the number of bytes copied to the target string.snprintfreturns the number of characters that would have been written to the target string. You can callsnprintfwith a null target and zero size to find out how many big a buffer is needed, then allocate the buffer and call it again to write to the target (NOTE: My original code sample had an off-by-one error.)Note that
snprintfwas added to C by the 1999 ISO standard. Microsoft’s compiler doesn’t appear to support it; it does provide a function it calls_snprintfwhich probably does the same thing.There’s also a GNU extension called
asprintfwhich does allocate the string for you:If you use this, you’ll have to use
free()later to deallocate the string. And since this is a GNU extension, it will make your code less portable.