Is it fine to use sizeof operator with "snprintf" ? for example
char cstring[20];
snprintf(cstring,sizeof(cstring),"%s","somestring......");
Yes, it's fine, the specific case you posted is good except that you don't check the return value, so you won't know if the string was truncated.
It is fine in example you posted.
However, it's not fine in any case where array decays in to pointer:
void func(char s []) {
snprintf(s,sizeof(s),"%s","somestring......"); // Not fine, s is actually pointer
}
int main(void) {
char cstring[20];
func(cstring); // Array decays to pointer
You can use the sizeof
operator in the snprintf
, but if the length of the string is bigger than the size which you have specified, then the remaining characters in the string will be lost.
Yes you can use. But if the string is higher than the sizeof value then the string is truncated. or up to the given value is stored in that array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With