我剛開始學習C語言,我不能完全理解為什么我們應該使用指標的指標來將一個元素附加到表中(*tab)。這是代碼:
#include "append.h"
int append(int ** tab, size_t *size, int value){
int *nouveauTab = realloc(*tab, (*size 1) * sizeof(int));
if (nouveauTab == NULL){
return 0;
}
*tab = nouveauTab;
(*tab)[*size] = value;
(*size) ;
return 1;
}
uj5u.com熱心網友回復:
如果不使用指向指標的指標,則指標選項卡將按值傳遞。即函式將處理原始指標值的副本。更改副本不會影響原始指標。它將保持不變,因為它的副本在函式內發生了變化。
所以你需要通過參考傳遞指標。
在 C 中,通過參考傳遞意味著通過指向它的指標間接傳遞一個物件(指標是一個物件)。因此取消參考該函式將直接訪問原始物件的指標。如果您的函式指向原始指標,例如
*tab = nouveauTab;
uj5u.com熱心網友回復:
簡短的回答是:因為您想更改append. 這發生在這里:*tab = nouveauTab;
呼叫您的append函式的代碼如下所示:
int* table = NULL;
size_t table_size = 0;
if (append(&table, &table_size, 42) == 0)
{
puts("append failed");
}
else
{
printf(size is now %zu and element %zu is %d", table_size, table_size-1, table[table_size-1]);
}
所以,你的代碼預期append(成功)會改變兩者的價值table和table_size。這要求您將函式指標傳遞給這兩個變數。
如果你在沒有usinb 指標的情況下這樣做,比如:
if (append(table, table_size, 42) == 0)
該函式將無法更改它們的值,因為 C 只會傳遞其當前值的副本。
一個簡單的例子使用 int
void foo(int x)
{
x = x 1;
printf("%d\n", x);
}
int x = 42;
printf("%d\n", x);
foo(x);
printf("%d\n", x);
將列印
42
43
42 <--- x not changed by `foo` because we passed the value of x (i.e. 42)
但有了這個:
void foo(int* x)
{
*x = *x 1;
printf("%d\n", *x);
}
int x = 42;
printf("%d\n", x);
foo(&x);
printf("%d\n", x);
它會列印
42
43
43 <--- x was changed by `foo` because we passed a pointer
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/349706.html
