简体   繁体   中英

warning: field width specifier '*' expects argument of type 'int', but argument 2 has type 'size_t' {aka 'long unsigned int'}

Code:

#include <stdio.h>
#include <string.h>

int main(void) {
    int number = 2;
    printf("%*s\n", strlen("foo") + number, "foo");
    return 0;
}

Warning:

prog.c: In function 'main':
prog.c:5:14: warning: field width specifier '*' expects argument of type 'int', but argument 2 has type 'size_t' {aka 'long unsigned int'} [-Wformat=]
     printf("%*s\n", strlen("foo") + number, "foo");
             ~^~     ~~~~~~~~~~~~~~~~~

Is it possible to eliminate this warning without casting the result of strlen() to an int , while keeping the width specifier as a variable? If yes, how?

printf expects an int for * , so just give it an int.-->> cast it to int.


printf("%*s\n", (int)(strlen("foo")+number), "foo");

But if you want to avoid the cast, you could use a variable for the length argument:


#include <stdio.h>
#include <string.h>

int main(void) {
    int number = 2;
    int fmtlen;

    fmtlen = strlen("foo") + number;
    printf("%*s\n", fmtlen, "foo");
    return 0;
}

Note: the correct types are essential for printf() s arguments, since it is a varargs function: the only way for printf to determine the types of its arguments is by inpecting the format string. And * expects an int.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM