Warning: format ‘%x’ expects argument of type ‘unsigned int’

cformat-specifiersprintf

When I try and compile this I get the following error, not sure why…

warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘char *’ [-Wformat=]

printf("Name buffer address:    %x\n", buffer);

The code:

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

main(){
        char name[200];
        printf("What is your name?\n");
        scanf("%s", name);
        bo(name, "uname -a");
}

int bo(char *name, char *cmd){
        char c[40];
        char buffer[40];
        printf("Name buffer address:    %x\n", buffer);
        printf("Command buffer address: %x\n", c);
        strcpy(c, cmd);
        strcpy(buffer, name);
        printf("Goodbye, %s!\n", buffer);
        printf("Executing command: %s\n", c);
        fflush(stdout);
        system(c);
}

Best Answer

You are getting the warnings because of the following statements

    printf("Name buffer address:    %x\n", buffer);
    printf("Command buffer address: %x\n", c);

%x expects an unsigned int, whereas you're supplying a pointer.

To refer, C11 standard, chapter §7.21.6.1

o,u,x,X
The unsigned int argument is converted to unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal notation (x or X) in the style dddd; [...]

Supplying invalid argument invokes undefined behavior.

You should be using %p to print the address

p The argument shall be a pointer to void.[...]

and cast the argument to void *, because for pointer types no default argument promotion takes place.

Having said that,

  1. main() should be int main(void), at least, to conform to the standard.
  2. You need to forward declare your function bo() because implicit declarations are bad and non-standard now.