1

I have the following define in a C code:

#define set_str(r,s) sprintf(r, "%-.*s", (int)sizeof(r)-1,s)

I tried calling the function set_str in my code to understand what the symbols mean, but it didn't give any special formatting or anything, the variable was just copied as it is. Can anyone tell me what is the meaning of this?

Mansuro
  • 4,194
  • 4
  • 31
  • 72

3 Answers3

5

It's nothing but the formatted output and some characters.

% --> means the character after % is the place holder and will be replaced by the respective argument.

But here few things came into picture that's why you are confused.

. --> Exactly * means sizeof(r)-1 space occupied

* --> which will specify the size or width of characters to be printed and * will be replaced by sizeof(r)-1.

- --> is for left adjustment or alignment.

last s --> will be replaced by s which is string.

Also sprintf() means printing to the buffer. In this case it's r.

EDIT : In case of . , See this general scenario of printing.

printf("%sx.yz",args); 
// just forget about the `args` it can be as many as the format specifiers,
// it's an example for one argument.

s = sign, can be `+` or `-`.`+` means right adjustment `-`means left adjustment. 
x = At least `x` characters wide.
y = Exactly `y` charactes wide.
z = format specifier like `s`,`d`,`f` and so on as for corresponding arguments. `
Omkant
  • 8,362
  • 7
  • 36
  • 57
2

The idea to specify width sizeof(r) -1 in sprintf() is to ensure that the destination buffer won't overflow.

This will not work when the r is a pointer as the sizeof(char*) won't give the size of characters allocated for it.

For example, if r is allocated as below the above macro would not work as desired.

char *r = malloc(50);
P.P
  • 106,931
  • 18
  • 154
  • 210
0

- is used for LEFT adjustment as @Omkant said, . for decimal and below post will better describe *..

What does the %*s format specifier mean?

Community
  • 1
  • 1
Adeel Ahmed
  • 1,543
  • 8
  • 10