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".
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.
Output
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