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?
You could do a macro
and then use this as
printf("%.*s\n", STR2(str)).Beware that this evaluates
STRtwice, 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
STRhas a field.lthat is a pointer and you’d only put a cast toint, all compilers would happily convert that pointer toint. Similar for the.sfield this really has to correspond to achar*or something compatible, otherwise you’d see a warning or error.