Compiler gives warning when printing the address of a variable

前端 未结 3 1017
一整个雨季
一整个雨季 2021-01-29 05:36

I made a very simple program to print the address of two variables.

#include

int main()
{
    int a,b;
    printf(\"%u\\n%u\",&a,&b);
            


        
3条回答
  •  失恋的感觉
    2021-01-29 06:10

    You got this error because format-specifier %u accepts unsigned-integer, whereas what you are supplying in your code is a pointer to a memory location.

    You can print address of memory location held by pointer by specifying type of the argument as (void*), this will generate no errors and print the address of memory location in decimal format.

    printf("%u\n%u",(void*)&a,(void*)&b);
    

    Also, this is not the correct way to print a pointer, the correct way is to use specifier %p, which will print the address of the memory location in hexadecimal format.

    printf("%p\n%p",(void*)&a,(void*)&b); 
    

    Hope that helps.

提交回复
热议问题