C 語言 講義 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 A B C
指標
用法:
int a;
int *p; // p 是指標, *p 是變數
例:
int a;
int *p;
a = 10;
p = &a;
完整的例子:
#include<stdio.h>
main()
{
int a;
int *p;
a = 10;
p = &a;
printf(" a : &a = %p , a = %d \n",&a,a);
printf(" p : p = %p , *p = %d \n",p,*p);
}執行結果 (有關位址的值 是會變動的)
a : &a = 0xfee91004 , a = 10
p : p = 0xfee91004 , *p = 10
實際應用:用來傳位址給自定函數
錯誤的例子: 交換的函數
#include <stdio.h>
void swap(int n1,int n2)
{
int t;
t=n1;
n1=n2;
n2=t;
}
main()
{
int x=4,y=8;
printf("before swap, x = %d,y = %d \n",x,y);
swap(x,y);
printf("after swap, x = %d,y = %d \n",x,y);
getchar();
}執行結果
before swap, x = 4,y = 8
after swap, x = 4,y = 8
正確的例子: 交換的函數
#include <stdio.h>
void swap(int *n1,int *n2)
{
int t;
t=*n1;
*n1=*n2;
*n2=t;
}
main()
{
int x=4,y=8;
printf("before swap, x = %d,y = %d \n",x,y);
swap(&x,&y);
printf("after swap, x = %d,y = %d \n",x,y);
getchar();
}執行結果
before swap, x = 4,y = 8
after swap, x = 8,y = 4
練習 1: 請設計一個計算x^y函數(計算x的y次方), 並以主程式呼叫它, 傳入 x, y, 計算結果會傳回主程式 (例如: x=5,y=3, 會傳回 125)