C 語言的參數傳遞都是 call by value 也就是在傳遞參數時會複製實參數值一份到函式中,所以如果我們想在建立一個函式的功能要改變變數的值亦須使用指標來完成例如以下
#include <stdio.h>
int swap(int *a,int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int a = 5, b = 3;
printf("Before swapping a=%d and b=%d\n",a,b);
swap(&a,&b);
printf("After swapping a=%d and b=%d",a,b);
}
那如果我們想改變的是指標變數的值呢?這時指標的指標就派上用場了
int gint = 0;
void changePtr (int **pInt)
{
*pInt = &gint;
}
void main ()
{
int local_int = 1;
int *localPtr = &local_int;
changePtr (&localPtr);
printf ("%d\n", *localPtr);
}