Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using size_t for specifying the precision of a string in C's printf

Tags:

c

c99

I have a structure to represent strings in memory looking like this:

typedef struct {
    size_t l;
    char   *s;
} str_t;

I believe using size_t makes sense for specifying the length of a char string. I'd also like to print this string using printf("%.*s\n", str.l, str.s). However, the * precision expects an int argument, not size_t. I haven't been able to find anything relevant about this. Is there someway to use this structure correctly, without a cast to int in the printf() call?

like image 772
Luci Stanescu Avatar asked Nov 10 '11 15:11

Luci Stanescu


2 Answers

printf("%.*s\n", (int)str.l, str.s)
//               ^^^^^ use a type cast

Edit

OK, I didn't read the question properly. You don't want to use a type cast, but I think, in this case: tough.

Either that or simply use fwrite

fwrite(str.s, str.l, 1, stdout);
printf("\n");
like image 139
JeremyP Avatar answered Oct 30 '22 11:10

JeremyP


You could do a macro

#define STR2(STR) (int const){ (STR).l }, (char const*const){ (STR).s }

and then use this as printf("%.*s\n", STR2(str)).

Beware that this evaluates STR twice, so be carefull with side effects, but you probably knew that already.

Edit:

I am using compound initializers such that these are implicit conversions. If things go wrong there are more chances that the compiler will warn you than with an explicit cast.

E.g if STR has a field .l that is a pointer and you'd only put a cast to int, all compilers would happily convert that pointer to int. Similar for the .s field this really has to correspond to a char* or something compatible, otherwise you'd see a warning or error.

like image 33
Jens Gustedt Avatar answered Oct 30 '22 11:10

Jens Gustedt