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讀取