pointers – How to print variable addresses in C?

pointers – How to print variable addresses in C?

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 dont forget the cast, e.g.

printf(%pn,(void*)&a);

When you intend to print the memory address of any variable or a pointer, using %d wont do the job and will cause some compilation errors, because youre trying to print out a number instead of an address, and even if it does work, youd 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: %pn, (void*) &a);
    return 0;
}

Good luck!

pointers – How to print variable addresses in C?

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);
}

Leave a Reply

Your email address will not be published.