我試圖了解指標的基本知識,并完成了以下代碼:
int c = 3;
int try(int a){
a;
return 0;
}
int main(){
try(c);
printf("%d\n",c);
return 0;
}
如何使用指標列印 4?我知道我可以這樣做:
int c = 3;
int try(int a){
a;
return a;
}
int main(){
c = try(c);
printf("%d\n",c);
return 0;
}
但我真的很想學習如何通過指標通過函式傳遞這些值。
此外,任何關于堅實 C 學習的好書推薦總是受歡迎的。提前致謝。
uj5u.com熱心網友回復:
int c = 3;
void pass_by_ref(int *a) // Take a Pointer to an integer variable
{
(*a); // Increment the value stored at that pointer.
}
int main(){
pass_by_ref(&c); // Pass the address of the variable to change
printf("%d\n",c);
return 0;
}
uj5u.com熱心網友回復:
這是如何做'c樣式通過參考'
int tryIt(int *a){
(*a);
}
int main(){
int c = 3;
tryIt(&c);
printf("%d\n",c);
return 0;
}
您將指標傳遞給變數并取消參考函式中的指標。該函式有效地“伸出”其范圍以修改傳遞的變數
請注意,我將 c 移到 main.c 中。在您的原始代碼中,“try”可能已經修改了 c 本身,因為它在全域范圍內。
并將“try”更改為“tryIt”——因為這看起來很奇怪
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/466500.html
上一篇:帶有指向函式的指標的C結構?
