![](/img/trans.png)
[英]Pointer to root node of B-tree after call to a function begins pointing to a child ( should continue pointing to root instead )
[英]Pointer not pointing to the correct array element after function call
我的主要功能中有兩個指針變量:largest_ptr和smallest_ptr。 任務是調用find_max_min()函數,將兩個數組(均為全局數組)中的最大和最小元素分配給各自的指針。
void find_min_max(uint8_t* a, uint8_t* b); //function declaration
uint8_t array1[] = { <some values> };
uint8_t array2[] = { <some values> };
int main(void)
{
uint8_t* largest_ptr;
uint8_t* smallest_ptr;
find_min_max(largest_ptr, smallest_ptr); //this does not assign any addresses
}
void find_min_max(uint8_t* largest, uint8_t* smallest){
//correct code to find the max/min in array1 and array2, and assign the addresses of the elements to largest and smallest
}
我嘗試調試find_min_max函數,結果是正確的,即正確的值已分配給最大和最小的指針。 但是,當我在main()中調用該函數時,相應的地址未分配給largest_ptr和smallest_ptr。 我做錯了什么嗎?
聚苯乙烯
對於未發布代碼,我深表歉意。 這是一個作業問題,可能會在竊測試中被發現。 我相信這足以解釋我的情況
通過它們的地址傳遞您的指針參數,以實現您的目標。
void find_min_max(uint8_t** a, uint8_t** b);
find_min_max(&largest_ptr, &smallest_ptr);
代替
void find_min_max(uint8_t* a, uint8_t* b);
smallest_ptr是類型指針的變量uint_8,並且它包含一個值是一個地址。 您創建的函數定義將最小聲明為另一個此類指針。 當執行函數調用時,將使用表達式的計算結果初始化最小的函數。 通常,此類表達式是文字或單個變量。 后者就是這種情況。 表達式minimum_ptr求值到某個地址,該地址通過值傳遞給函數,即-分配給minimum 。
盡管我看不到函數的內部工作原理,但我假設您不是從small讀取,而是向其寫入。 但是最小的是局部變量,其范圍和生存期與該函數相關。 您寫入此變量,然后結果將丟失。
您想要實現的是在功能范圍之外操作某些數據。 一種可能是通過這樣聲明的參數將數據的地址提供給函數:
func( TYPE* x)
{
//...
*x = VALUE; // we don't want to set local variable,
// but the variable being pointed to by it, so we dereference the local pointer
}
像這樣調用:
TYPE y;
func(&y);
其中&是地址運算符,因此我們提供y的地址以使func()函數能夠寫入。
由於在您的情況下,需要操縱的變量是指向uint8_t的指針,因此您需要傳遞指針的地址,因此局部變量必須是指向指針的指針-func(int ** x);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.