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