Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it fine to use sizeof operator in snprintf

Tags:

c

Is it fine to use sizeof operator with "snprintf" ? for example

   char cstring[20];
   snprintf(cstring,sizeof(cstring),"%s","somestring......");
like image 799
Rahul_cs12 Avatar asked Dec 19 '14 06:12

Rahul_cs12


4 Answers

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.

like image 145
John Zwinck Avatar answered Nov 14 '22 10:11

John Zwinck


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
like image 43
user694733 Avatar answered Nov 14 '22 08:11

user694733


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.

like image 31
sharon Avatar answered Nov 14 '22 10:11

sharon


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.

like image 2
Karthikeyan.R.S Avatar answered Nov 14 '22 09:11

Karthikeyan.R.S