c++ scanf读取
Here, we have to input a valid memory address and print the value stored at memory address in C.
在这里,我们必须输入一个有效的内存地址并在C中打印存储在内存地址中的值。
To input and print a memory address, we use "%p" format specifier – which can be understood as "pointer format specifier".
要输入和打印内存地址,我们使用“%p”格式说明符-可以理解为“指针格式说明符” 。
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.
在此程序中-首先,我们声明一个名为num的变量,并在其中分配任何值。 由于我们无法预测有效的内存地址。 因此,在这里,我们将打印num的内存地址,然后从用户读取并打印其值。
#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.
在此程序中,我们声明了一个名为num的无符号int变量,并为其分配了值123 。
Then, we print the value of num by using "%p" format specifier – it will print the memory address of num – which is 0x7ffc505d4a44.
然后,我们使用“%p”格式说明符打印num的值-它会打印num的内存地址-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).
然后,我们提示消息“现在,读取/输入内存地址:”以输入内存地址-我们输入与num的内存地址相同的内存地址。 输入值为7ffc505d4a44 。 并将存储的地址存储到指针变量ptr中 。 (您必须知道只有指针变量才能存储内存地址。更多:C语言指针)。
Note: While input, "0x" is not required.
注意:输入时,不需要“ 0x” 。
And finally, when we print the value using the pointer variable ptr. The value is 123.
最后,当我们使用指针变量ptr打印值时。 值是123 。
翻译自: https://www.includehelp.com/c-programs/read-a-memory-address-using-scanf-and-print-its-value.aspx
c++ scanf读取