我有一個簡單的程式
int main()
{
int a = 1; // variable declaration
printf("a before: %d \n", a); // a is 1
int* b = &a; // pointer declaration - get the memory address of variable `a` with the `&` reference opeartor
*b = 2; // dereference to access data contained the memory block of variable `a` via the the `*` dereference operator
printf("a after : %d", a); // a becomes 2
return 0;
}
我想知道哪種心理模型是正確的:
假設變數
a指向存盤100000f91資料的記憶體地址int 1。通過執行此分配,*b = 2我們將內容/資料從 更改為int 1,int 2但資料仍位于原始記憶體地址中,即100000f91。通過這個賦值
*b = 2,我們改變了變數a從記憶體地址100000f91指向的其他地方,例如100000f92新資料int 2的存盤位置。
如果我在這里錯了,請隨時糾正我。無論哪種心智模型是正確的,我想知道當我們通過a參考傳遞一個函式時,相同的心智模型是否仍然適用
void fn(int* b) {}
uj5u.com熱心網友回復:
變數的地址在其生命周期內永遠不會改變。
這意味著直接更改變數的值:
a = 2;
或間接地:
b = &a;
*b = 2;
永遠不要改變它的地址。所以你的第一個心智模型是正確的。
此外,這種說法是不正確的:
假設變數 a 指向記憶體地址
a不是指標型別,因此它不指向地址。像所有變數一樣,它有一個不會改變的地址。
uj5u.com熱心網友回復:
變數a不會在記憶體中移動。變數的記憶體在a定義后立即分配。
變數a無處可去。它旨在存盤型別的物件int。
它是b存盤變數地址的指標a
int* b = &a;
因此,取消參考指標,我們可以訪問為變數分配的記憶體,a并可以更改該記憶體中存盤的物件。
這是一個演示程式,可以幫助您輕松理解。
#include <stdio.h>
int main( void )
{
int a = 1;
printf( "The address of the variable a is %p\n", ( void * )&a );
int *b = &a;
printf( "The address stored in the variable b is %p\n", ( void * )b );
*b = 2;
printf( "After the assignment the address of the variable a is %p\n", ( void * )&a );
}
程式輸出可能看起來像
The address of the variable a is 006FF9D4
The address stored in the variable b is 006FF9D4
After the assignment the address of the variable a is 006FF9D4
正如你在分配后看到的
*b = 2;
變數的地址a沒有改變。它是存盤在a被更改的變數占用的記憶體中的值。
您可以將變數視為記憶體的命名范圍,旨在存盤用于宣告變數的指定型別的物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409051.html
標籤:
