How to print variable addresses in C?

前端 未结 5 1267
孤独总比滥情好
孤独总比滥情好 2020-11-29 23:32

When i run this code.

#include 

void moo(int a, int *b);

int main()
{
    int x;
    int *y;

    x = 1;
    y = &x;

    printf(\"Addr         


        
相关标签:
5条回答
  • 2020-11-30 00:08

    Looks like you use %p: Print Pointers

    0 讨论(0)
  • 2020-11-30 00:09

    You want to use %p to print a pointer. From the spec:

    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.

    And don't forget the cast, e.g.

    printf("%p\n",(void*)&a);
    
    0 讨论(0)
  • 2020-11-30 00:09

    When you intend to print the memory address of any variable or a pointer, using %d won't do the job and will cause some compilation errors, because you're trying to print out a number instead of an address, and even if it does work, you'd have an intent error, because a memory address is not a number. the value 0xbfc0d878 is surely not a number, but an address.

    What you should use is %p. e.g.,

    #include<stdio.h>
    
    int main(void) {
    
        int a;
        a = 5;
        printf("The memory address of a is: %p\n", (void*) &a);
        return 0;
    }
    

    Good luck!

    0 讨论(0)
  • 2020-11-30 00:10

    I tried in online compiler https://www.onlinegdb.com/online_c++_compiler

    int main()
    {
        cout<<"Hello World";
        int x = 10;
        int *p = &x;
        printf("\nAddress of x is %p\n", &x); // 0x7ffc7df0ea54
        printf("Address of p is %p\n", p);    // 0x7ffc7df0ea54
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-30 00:33

    To print the address of a variable, you need to use the %p format. %d is for signed integers. For example:

    #include<stdio.h>
    
    void main(void)
    {
      int a;
    
      printf("Address is %p:",&a);
    }
    
    0 讨论(0)
提交回复
热议问题