0

I'm wondering if this is the proper way to concatenate and NUL terminate strings including width.

#define FOO "foo"
const char *bar = "bar";
int n = 10;
float f = 10.2;

char *s;
int l;

l = snprintf (NULL, 0, "%-6s %-10s %4d %4f",FOO, bar, n, f);
s = malloc (l + 4); // should it be the number of formats tags?
if (s == null) return 1;
sprintf (s, "%-6s %-10s %4d %4f", FOO, bar, n, f);
3
  • It might be a good idea for maintenance purposes to define one format string that is used by both the snprintf and the sprintf. It'd really suck if it got changed in one place and not the other! Commented Dec 8, 2010 at 3:23
  • That sounds like a good idea, would it be possible to post a sample code in reference to this? Thanks Commented Dec 8, 2010 at 3:27
  • 1
    Just declare something like const char* fmt_str = "%-6s %-10s %4d %4f"; and use that as your format string in both places. Commented Dec 8, 2010 at 3:31

2 Answers 2

1

Quite a few systems have a function asprintf in their standard C libraries that does exactly what you do here: allocate and sprintf.

Sign up to request clarification or add additional context in comments.

Comments

0

You only need to add 1 to the value returned by snprintf(), since there is only one null terminator added.

However, you do need to check for l == -1 (indicating that snprintf() failed).

2 Comments

snprintf isn't defined in the original C89, and I think that there were a few platforms with non-C99-compliant implementations, but C99 does say that snprintf(NULL, ...) is supposed to work the way OP uses it here.
@ephemient: Quite so, I've removed that bit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.