Q:

Read a memory address using scanf() and print its value in C

belongs to collection: C scanf() Programs

0

Read a memory address using scanf() and print its value in C

Here, we have to input a valid memory address and print the value stored at memory address in C.

To input and print a memory address, we use "%p" format specifier – which can be understood as "pointer format specifier".

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

In this program - first, we are declaring a variable named num and assigning any value in it. Since we cannot predict a valid memory address. So here, we will print the memory address of num and then, we will read it from the user and print its value.

#include <stdio.h>

int main(void) 
{

	int num = 123;
	int *ptr; //to store memory address

	printf("Memory address of num = %p\n", &num);

	printf("Now, read/input the  memory address: ");
	scanf ("%p", &ptr);

	printf("Memory address is: %p and its value is: %d\n", ptr, *ptr);

	return 0;
}

Output

Memory address of num = 0x7ffc505d4a44
Now, read/input the  memory address: 7ffc505d4a44
Memory address is: 0x7ffc505d4a44 and its value is: 123 

Explanation:

In this program, we declared an unsigned int variable named num and assigned the variable with the value 123.

Then, we print the value of num by using "%p" format specifier – it will print the memory address of num – which is 0x7ffc505d4a44.

Then, we prompt a message "Now, read/input the memory address: " to take input the memory address – we input the same memory address which was the memory address of num. The input value is 7ffc505d4a44. And stored the memory address to a pointer variable ptr. (you must know that only pointer variable can store the memory addresses. Read more: pointers in C language).

Note: While input, "0x" is not required.

And finally, when we print the value using the pointer variable ptr. The value is 123.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Skip characters while reading integers using scanf... >>
<< Input individual characters using scanf() in C...