But my c compiler doesn't seem to support snprintf. What alternative do i have?
If you're using GCC/Clang, you can turn on C99 mode (default is C89, I believe). snprintf is part of the C99 standard, not the C89 standard. To turn on C99 mode with GCC or Clang, just pass the -std=c99 flag to the compiler when compiling. Or change your IDE to use C99 mode if you're using an IDE.
If you're using MSVC... it's a bit tricker, see below.
Just use memcpy.
You should try to avoid the printf functions if you don't need the advanced formatting they provide.
a) Unless you have good reason to, don't worry about premature optimization. b) memcpy isn't necessarily a good replacement. I specifically used snprintf because it always null terminates the string. Always. memcpy does not, nor does strncpy. Yes, he can use memcpy, but he would have to 1) determine how long the source buffer is, 2) determine how long the dest buffer is, 3) pick the min of the two, 4) ensure the copied string is null terminated. It's certainly possible to use memcpy, but judging by his skill level, I think it's more worthwhile to suggest things that are less likely to lead him to screwing up (or at the very least, pointing out the caveats of alternative methods).
Which compiler are you using? It may have snprintf(), but with a different spelling. Ex: MSVC calls it _snprintf().
It should also be pointed out that there are a few gotchas if you use MSVC's _snprintf. Most notably, _snprintf does not necessarily null terminate the string (like snprintf always does). Additionally, the return values are different. Before anyone uses _snprintf, they should first read this.
Edited by Cornstalks, 27 June 2013 - 02:01 PM.