(I've seen questions 19202368, 40095973 and 1775403)
I have this:
char data[32];
memset(data, '\0', sizeof(data));
snprintf(data, sizeof(data), "%s - %d", aCharArray != NULL ? aCharArray : "", anInt);
which yields this warning when compiling on some compilers/architectures:
warning: argument to 'sizeof' in 'int snprintf(char*, size_t, const char*, ...)' call is the same expression as the destination; did you mean to provide an explicit length? [-Wsizeof-pointer-memaccess]
Both aCharArray
and anInt
may be local to the function or passed as arguments. This is a generic example and this is the generic approach I use (using memset
to initialize and preferring snprintf
to sprintf
). I know that if data
is local I can use the same size I used to declare it but I prefer to only specify the size in the declaration, once; this way it's easier to change in the future.
Also, snprintf
will avoid overflows and put the \0
at the end. strlen
will work for a char*
passed as argument to the function but it'll be pointless on a freshly initialized or empty (i.e. ""
) char[]
.
So, I'm not providing the string length as it may be 0, but I do want to provide the array's size.
Is this approach correct or am I missing some caveat?
On a side note, what's the compiler flag to identify switched parameters? I.e., using the above:
snprintf(data, sizeof(data), "%s - %d", anInt, aCharArray);