簡體   English   中英

使用指針通過引用傳遞數組感到困惑

[英]confusion with passing arrays by reference using pointers

幾個小時前我剛剛問了一個問題,我對答案中指出的東西( 在c ++中使用指針的數組:訪問返回的數組時出現段錯誤 )完全感到困惑。 有些人對我的newb問題一直持否定的態度,所以我瀏覽了有關指針的書,但對我沒有多大幫助。 所以,我再來一次。

在上一個問題中,我有一個函數void builder(int aSize1, int aSize2, int aSize3, int*** frequencies) ,我認為它將為分配給int*** frequencies參數的3d數組動態分配內存並進行初始化它。 但是,有人告訴我,只有一個副本會傳遞到函數中,而我只是為副本而不是原始副本分配和初始化。 因此,他們建議我改用引用,將函數原型呈現為void builder(int aSize1, int aSize2, int aSize3, int***& frequencies)

但是,我回想起就在昨天,當我第一次偶然發現使用指針進行按引用傳遞的概念時,也將能夠操縱指針的數據。 以機智,

void change_what_this_points_to( int* a )
{
    *a = 42;
}

此函數的確更改了饋入該函數的指針的值。

所以,我的問題是,為什么前者通過副本而后者通過真實交易 除了一個星號更多的事實之外,我沒有看到這兩個函數之間有多少區別。

任何幫助,將不勝感激。 謝謝!

雖然另一個答案說的很完美,但我只是想加兩美分,以防萬一。 可以將指針視為內存中的地址。 您將該地址傳遞給函數,然后函數在其中寫入內容。 然后,在調用該函數之后,您可以在內存中的同一位置查看並查看其中的值。

因此,假設您具有以下代碼:

void SetValue(int *a){ *a = 10;}
void DoWork()
{
    int a; 
    SetValue(&a); 
}

SetValue函數將指向int的指針作為參數,或者我們將其視為存儲int的內存中的地址作為參數。 然后,該函數僅將數字10寫入傳入的地址。

然后,DoWork方法為int創建內存,並將該內存的地址傳遞給函數。 因此,在DoWork返回存儲“ a”的內存時,其值為10。聽起來好像您的問題中已有此內容,但為了以防萬一,請從此處開始。

現在,讓我們假設您想要一個函數為您分配內存。 您真正要求函數執行的操作是分配內存,並告訴我該內存在哪里。 所以你可以用一個指針返回值來做到這一點,即

int* AllocateMemoryForMe()
{
    return new int(); //Creates memory for an int, let's pretend it's at location 0x100
}
void DoWork()
{
    int* a = NULL; // a has a value of 0x00
    a = AllocateMemoryForMe(); //a will now have the value of 0x100
    *a = 10; //We now write 10 to memory location 0x100
}

或者,您可以使用指針執行此操作。 如果這樣做,實際上需要做的就是將函數中的一個位置傳遞到函數中,以將已分配內存的地址寫入其中,從而獲得指向指針的指針。 因此,當函數返回時,您可以查看該地址,並查看新創建的內存的地址。 因此,例如:

void AllocateMemoryForMe(int** x)
{
    *x = new int(); //allocates memory for an int, let's pretend it's at memory location 0x200
}
void DoWork()
{
    int** a = new int*(); //Creates memory for an int pointer. Let's pretend it allocates memory at location 0x100. 
    AllocateMemoryForMe(a); //pass memory location 0x100 to the function.
    //Right now the address of a is still 0x100 but the data at the memory location is 0x200. This is the address of the int we want to write to.
    **a = 10; //This will now write 10 to the memory location allocated by the AllocateMemoryForMe() function. 

}

該功能

void change_what_this_points_to( int* a )
{
    *a = 42;
}

不會更改指針本身。 它更改指針指向的整數對象。

如果要更改指針本身,則應按以下方式編寫函數

void change_what_this_points_to( int * &a )
{
    a = new int( 42 );
}

或以下方式

void change_what_this_points_to( int **a )
{
    *a = new int( 42 );
}

因此,返回到函數,您應該像這樣聲明它

void builder(int aSize1, int aSize2, int aSize3, int*** &frequencies);

或喜歡

void builder(int aSize1, int aSize2, int aSize3, int**** frequencies);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM