Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ printf field width specifier ‘.*’ expects int not size_t

Tags:

c++

printf

I'm in the process of fixing compiler warnings in a legacy project I inherited. New compiler is gcc version 4.8.5 20150623 (Red Hat 4.8.5-4) (GCC).

Their is lots of code like the following:

#include <cstdio>
#include <cstring>

struct foobar
{
    char field1[10];
    char field2[5];
};

int main()
{
    struct foobar foo;
    memset(&foo, ' ', sizeof(foo));
    strncpy(foo.field1, "1234567890", sizeof(foo.field1));

    // Produces warning
    printf("[%.*s]", sizeof(foo.field1), foo.field1);

    return 0;
}

This produces a warning messages:

1_test.c: In function ‘int main()’:
1_test.c:16:49: warning: field precision specifier ‘.*’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]
  printf("[%.*s]", sizeof(foo.field1), foo.field1);

This seems wrong to me as '.*' SHOULD expect a size_t but apparently it doesn't...

Is there anyway to fix this problem globally besides having to do something like the following:

    // Fixes
    printf("[%.10s]", foo.field1);

    // Fixes
    printf("[%.*s]", static_cast<int>(sizeof(foo.field1)), foo.field1);
like image 843
LeviX Avatar asked Oct 30 '22 02:10

LeviX


1 Answers

Proper solution would be:

std::cout << std::string( foo.field1, sizeof( foo.field1 ) );

this would output what you desire and no warnings generated. But better solution fo course would be to use std::string in struct foobar

like image 79
Slava Avatar answered Nov 02 '22 10:11

Slava