簡體   English   中英

如何在函數返回的數組中保留指向元素的指針?

[英]How do I keep a pointer to an element in an array that is returned from a function?

我有很多。 我將此數組提供給一個函數,該函數返回指向數組中特定元素的指針。 或者,至少這應該發生。 相反,函數返回后我得到的指針是0x0000。 什么?!

int* getPtr(int[] array)
{
    //there is guarenteed no indexOutOfBounds...
    fixed(int* p = array[4])
    return p;
}


Main()
{
    int[] massive = new int[10];
    int* p = getPtr(massive);
    Console.WriteLine((int)p);        //... address is 0... arg
}

我會嘗試先給數組一些值。 如果您只寫了一個指向其中沒有數據的存儲位置的指針,則無法保證返回的內容。

由固定完成的fixed僅持續到受控語句(或塊)的末尾。 因此,您的代碼等效於:

fixed(int* p = array[4]) {
    return p;
}

函數返回后,固定不再有效。 文檔中

執行該語句中的代碼后,所有固定的變量都將取消固定並進行垃圾回收。 因此,不要指向固定語句之外的那些變量。

暫無
暫無

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

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