Home » C solved programs » C basic programs

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.

Program:

#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

Program:

#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.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.