Warning C4477 in Visual Studio 2015

14,971

Solution 1

Because you are using incorrect format specifier. %d is to print an int. To print pointers use %p and cast to void*:

printf("Address of num: %p Value: %d\n", (void*)&num, num);
printf("Address of pi: %p Value: %p\n", (void*)&pi, (void*)pi);

The cast to void* is needed because variadic functions don't do any type conversions from type * to void * as required for %p. Quoting the standard:

7.21.6 Formatted input/output functions (C11 draft)

p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

Solution 2

Said another way, your argument &num (or in the form (void *) &num) is telling the compiler that you wish to pass in to the function the address of num, not the value of num. The printf function with it's %d format specifier is expected a value, not an address. The complaint is the compiler realizing this difference.

Note: in the 32 bit work, an address and an int are both 32 bits and so things (i.e. the %d) would just work. But, in the 64 bit world, an int is still 32 bits long but an address is 64 bits. I.E. you can't accurately represent the value of the pointer with a %d. That's why %p got created. It (the compiler) is smart enough to handle a %p parameter as a 32 bit quantity when compiled for 32 bits and a 64 bit quantity when compiled for 64 bits.

Read up on computer architecture, hardware stacks and their bit sizes. While you're at it you may also wish to understand the difference between little endian and big endian.

Share:
14,971

Related videos on Youtube

Adonaim
Author by

Adonaim

Updated on September 14, 2022

Comments

  • Adonaim
    Adonaim over 1 year

    When I compile the following code, Visual studio shows warning of C4477. Why this warning generated by visual studio? And How can I fix this code?

    warning : warning C4477: 'printf' : format string '%d' requires an argument of type 'int', but variadic argument 1 has type 'int *'

    #include <stdio.h>
    
    int main(void) {
        int num = 0;
        int *pi = &num;
    
        printf("Address of num: %d Value: %d\n", &num, num);
        printf("Address of pi: %d Value: %d\n", &pi, pi);
    
        return 0x0;
    }
    
    • too honest for this site
      too honest for this site over 8 years
      %d expects an int argument. To print a pointer use %p. Please read the man-page of printf or search for "printf format string"!