Printing an address of a variable in C

Here, we are going to learn how to print the memory address of a variable in C programming language? To print the memory address, we use '%p' format specifier in C.
Submitted by IncludeHelp, on September 13, 2018

To print the address of a variable, we use "%p" specifier in C programming language. There are two ways to get the address of the variable:

  1. By using "address of" (&) operator
  2. By using pointer variable

1) By using "address of" (&) operator

When we want to get the address of any variable, we can use “address of operator” (&) operator, it returns the address of the variable.

Example to print an address of a variable in C using address of operator

#include <stdio.h>

int main(void)
{
    // declare variables 
    int a;
    float b;
    char c;

    printf("Address of a: %p\n", &a);
    printf("Address of b: %p\n", &b);
    printf("Address of c: %p\n", &c);

    return 0;
}

Output

Address of a: 0x7ffd3d518618
Address of b: 0x7ffd3d51861c
Address of c: 0x7ffd3d518617

2) By using pointer variable

A pointer is the type of a variable that contains the address of another variable, by using the pointer; we can also get the address of another variable.

Read more: Pointers in C language

Example to print an address of a variable in C using pointer

#include <stdio.h>

int main(void)
{
    // declare variables 
    int a;
    float b;
    char c;
	
    //Declare and Initialize pointers 
    int *ptr_a = &a;
    float *ptr_b = &b;
    char *ptr_c = &c;
	
    //Printing address by using pointers 	
    printf("Address of a: %p\n", ptr_a);
    printf("Address of b: %p\n", ptr_b);
    printf("Address of c: %p\n", ptr_c);

    return 0;
}

Output

Address of a: 0x7ffd3d518618
Address of b: 0x7ffd3d51861c
Address of c: 0x7ffd3d518617

Note: At every run output may change.

C Basic Programs »


Related Programs

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.