雖然兩者都使用pass-by-value
來傳遞參數,但它們的使用方式有很大的不同。當您將指針作爲參數傳遞給函數時,無論您通過取消引用在函數體指針反映在這些指針指向變量的原始值,儘管這些passed pointers
可main()
宣佈的「原始」的指針。你看,多個指針可以指向一個副本變量,因此變量的值可以通過解引用任何這些指針來改變。
但是,雖然您將變量作爲參數傳遞而不是指針,但對這些變量的值的所有操作都不會反映在「原始」變量的值中。這些更改僅限於那些作爲參數傳遞的copies
。
在您的例子中,如果你想分配的return of foo()
值還是那doSomething()
比bar
以外的變量,並打算不改變bar
的值,那麼只有通過變量參數是可取的,不是指針。
下面是一些簡單的代碼示出它:
// Passing variables as arguments
#include<stdio.h>
int foo(int bar){
bar=303;
}
int main(void)
{
int foobar = 0;
printf("The value of foobar before function call is %d\n",foobar);
foo(foobar);
printf("TThe value of foobar after function call is %d",foobar);
}
輸出:The value of foobar before function call is 0
`The value of foobar after function call is 303`
// Passing pointers to variables as arguments
#include<stdio.h>
int doSomething();
int foo(int *bar){
*bar = doSomething();
}
int main(void){
int foobar = 0;
printf("The value of foobar before function call is %d\n",foobar);
foo(&foobar);
printf("TThe value of foobar after function call is %d",foobar);
}
int doSomething()
{
return 303;
}
輸出:The value of foobar before function call is 0
`The value of foobar after function call is 0`
,最後,約指針使代碼複雜,好了,指針是C的最優雅的特點之一,是一旦你一個非常有用的和不可缺少的工具知道如何很好地使用它們。
請閱讀更多關於指針的信息,這是一個非常強大的工具,它不僅僅是語法問題。 – Guy 2013-04-28 04:35:06
我想你的意思是'foo(&foobar)'在第一個例子中。 – 2013-04-28 04:35:31
通過使用指針,您不會返回,因爲您傳遞參數的地址,並且它被修改。但是使用方法,一旦它們退出函數,就會離開堆棧,因此您需要返回值。 – Sunny 2013-04-28 04:38:02