[英]Simple Function in C pointer vs passed value
我只想確認一下,當我具有某種功能時
int subtract(int a, int b)
{
return a-b;
}
我在調用減法(3,2)而不是指針時傳遞值。
謝謝,
是的,你是
int a
的參數意味着將值按整數傳遞給函數 int* a
的參數int* a
意味着將指向某個整數的指針傳遞給該函數。 所以為此
int subtract(int a, int b)
{
// even if I change a or b in here - the caller will never know about it....
return a-b;
}
您這樣稱呼:
int result = substract(2, 1); // note passing values
對於指針
int subtract(int *a, int *b)
{
// if I change the contents of where a or b point the - the caller will know about it....
// if I say *a = 99; then x becomes 99 in the caller (*a means the contents of what 'a' points to)
return *a - *b;
}
您這樣稱呼:
int x = 2;
int y = 1;
int result = substract(&x, &y); // '&x means the address of x' or 'a pointer to x'
是的,C始終按值傳遞函數參數。 要傳遞指針,您必須指定標識指針類型的星號(星號)。
請記住,即使在使用指針的情況下, C也總是通過值函數參數傳遞值 ,在這種情況下,實際上是復制了指針的地址。
是的,您正在傳遞價值。 指針將在類型名稱之后和變量名稱之前用星號表示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.