-2

Following the answer of here, I wanted to see how many bytes a snprintf uses. The following code

#include "stdio.h"

int main() {
    printf("%d\n", snprintf(NULL, 0, "%d:%llx:%d:%llx:%llx:%llx", 0, 0, 0, 0, 0, 0));
    printf("%d\n", snprintf(NULL, 0, "%d:%llx:%d:%llx:%llx:", 0, 0, 0, 0, 0));
    printf("%d\n", snprintf(NULL, 0, "%llx", 0));
    return 0;
}

returns

22
10
1

I do not understand how the %llx at the end of other data printed can use 12 bytes while it uses only 1 byte if it is used alone. Does snprintf do any byte alignment?

Joe C
  • 2,757
  • 2
  • 26
  • 46

1 Answers1

3

Your code has a bug. The %llx format specifier is only for long longs. Try:

#include "stdio.h"

int main() {
    printf("%d\n", snprintf(NULL, 0, "%d:%llx:%d:%llx:%llx:%llx", 0, 0LL, 0LL, 0LL, 0LL, 0LL));
    printf("%d\n", snprintf(NULL, 0, "%d:%llx:%d:%llx:%llx:", 0, 0LL, 0LL, 0LL, 0LL));
    printf("%d\n", snprintf(NULL, 0, "%llx", 0LL));
    return 0;
}
David Schwartz
  • 179,497
  • 17
  • 214
  • 278