一個(gè)函數如果不是傳遞指針,那么在實(shí)際調用過(guò)程中會(huì )生成一個(gè)臨時(shí)變量替代這兩個(gè)傳入的參數:
#include <stdio.h>
void add(int a, int b)
{
printf("the address of a and b is: %x %x\n",&a,&b);
}
int main()
{
int a=100, b=1;
printf("the address of a and b is: %x %x\n",&a,&b);
add(a,b);
}
==================================================================
the address of a and b is: 22ff74 22ff70
the address of a and b is: 22ff50 22ff54
可以看到實(shí)際的參數已經(jīng)被替代了。
那么如果傳遞指針的情況下又是什么樣的呢?
#include <stdio.h>
void add(int *a, int *b)
{
printf("the content of a and b is: %x %x\n",a,b);
printf("the address of a and b is: %x %x\n",&a,&b);
}
int main()
{
int x=100, y=1;
int *a=&x, *b=&y;
printf("the content of a and b is: %x %x\n",a,b);
printf("the address of a and b is: %x %x\n",&a,&b);
add(a,b);
}
==============================================================
the content of a and b is: 22ff74 22ff70
the address of a and b is: 22ff6c 22ff68
the content of a and b is: 22ff74 22ff70
the address of a and b is: 22ff40 22ff44
可以看到實(shí)際傳遞的指針也被兩個(gè)臨時(shí)的指針替代了,但是指針所指的地址沒(méi)有改變。
所以我們在函數內對指針所指向的地址做的修改不會(huì )對實(shí)際的傳入的指針所指地址造成修改,但是如果對所指內容做修改則會(huì )修改相應的實(shí)際數據。
在C++中又看到這樣的話(huà):
如果參數是指針,且僅作輸入用,則應在類(lèi)型前加const,以防止該指針在函數體內被意外修改。
例如:
void StringCopy(char *strDestination,const char *strSource);
在我們加了const之后則沒(méi)有辦法對所指內容做修改,否則會(huì )出現編譯錯誤,但是我們還是可以改變指針指向地址,這已經(jīng)無(wú)所謂了,實(shí)際的指向地址是不會(huì )改變的。
認識到所有的傳入參數都會(huì )在編譯器中為它分配一個(gè)臨時(shí)copy
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。