2011年10月15日 星期六

C 傳址呼叫 (pass by value) & 傳指標呼叫(pass by pointer)

傳值呼叫(pass by value):
在呼叫函數時,只傳引數的"數值"給函式,函式不可能會改變原本呼叫方的引數數值 ,

#include <stdio.h>
#include <stdlib.h>

void func1(int a,int b)
{
  a=a+10;
  b=b+20;
  printf(" %d,",a);
  printf(" %d ",b);     
}

int main()
{
  int x=1;
  int y =2;
  func1(x,y);  
  printf(" %d,",x);
  printf(" %d ",y); 
  system("pause"); 
  
}

RESULT:11,22,1,2

傳指標呼叫(pass by pointer):
仍是傳值呼叫的一種,不過傳入的是引數的記憶體位址,函式會改變原本呼叫方的引數數值,不會改變該引數在記憶體裡的位址

 #include <stdio.h>
#include <stdlib.h>

void func1(int *a,int b)
{
  *a=*a+10;
  b=b+20;
  printf(" %d,",*a);
  printf(" %d ",b);    
}

int main()
{
  int x=1;
  int y =2;
  func1(&x,y); 
  printf(" %d,",x);
  printf(" %d ",y);
  system("pause");
 
}
 RESULT:11,22,11,2
//pass by pointer 會改變Caller的變數值,因為傳指標呼叫,指標變數指向該變數的記憶體位址

沒有留言:

張貼留言