很容易混淆的概念其實並不難理解
1,指針數組;
看字面意思就知道這一定是一個數組,裏面的原酸全部是指針
例如,定義一個簡單的指針數組
char *p[10]; //這就是一個包含十個字符指針的數組。
例:
#include<stdio.h>
int main()
{
char *p[7];
char arr[] = "abcdef";
int i = 0;
for (i = 0; i < 7; i++)
{
p[i] = arr;
}
printf("%s", p[6]);
}
輸出結果是abcdef.
這個簡單的程序就用到了指針數組,他定義了一個數組包含了7個字符指針,for循環每一個指針都指向了arr數組定義的字符串。
2,數組指針
從名字上看就能知道他是一個指針,是一個指向數組的指針。
例如:
#include<stdio.h>
int main()
{
char arr[6] = "abcde";
char(*p)[6] = &arr; //數組指針才能取數組的地址。
printf("%s", *p);
}
這個簡單的程序最後的輸出結果當然是arr字符數組中的內容了。
通過數組指針也能更改數組中的內容,對於上面的程序*((*p)+1)='a';就把第二個元素改成了‘a’;*p便是arr的地址。
3,函數指針
一樣,從名字上看,這便是一個指向函數的指針,他是如何定義的呢,
例:
int num(int a,int b)
{
return a+b;
}
int mian()
{
int (*p)(int ,int )=num; //這便是一個指向num函數的一個函數指針了,int 是函數的返回值,
後面是數據類型,它所指向的函數必須和他有同樣的返回值和數據類型。
int ret=(*p)(10,20);
printf("%d",ret);//結果是30.
}
4,函數指針數組
從名字上也能看楚這首先是一個數組,數組元素是指針,而每一個指針都指向了一個函數,這個麻煩的東西有什麼用了,
事實證明他在某些地方非常有用處,首先來看他是如何定義的
例:
int (*p[4])(int ,int)
//這便是一個有4個元素的函數指針數組了,這個數組中的每一個指針指向的函數必須是一樣的數據類型和返回值。
具體有什麼用我們來看一段代碼。
這個代碼是一個簡單的計算器。
#include <stdio.h>
void print_menu()
{
printf("**********************\n");
printf("*** 1.add 2.sub ***\n");
printf("*** 3.mul 4.div ***\n");
printf("******* 0 exit ******\n");
printf("**********************\n");
}
int add(int x, int y)
{
return x + y;
}
int sub(int x, int y)
{
return x - y;
}
int mul(int x, int y)
{
return x * y;
}
int div(int x, int y)
{
if (y == 0)
{
printf("除數爲0\n");
return -1;
}
return x / y;
}
int(*pfun[5])(int, int) = {0,add, sub, mul, div};
//函數指針的數組(轉移表)
int main()
{
int input = 1;
while (input)
{
int n1 = 0;
int n2 = 0;
int ret = 0;
print_menu();
printf("請選擇>:");
scanf("%d", &input);
printf("請輸入兩個操作數>:");
scanf("%d%d", &n1, &n2);
ret = pfun[input](n1, n2);
/*switch (input) //如果不用函數指針數組便要用switch來實現,可以看出如果計算器功能很多,那麼
代碼也會相當龐大
{
case 1:
ret =add(n1,n2);
break;
case 2:
ret = sub(n1, n2);
break;
case 3:
ret = mul(n1, n2);
break;
case 4:
ret = div(n1, n2);
break;
}*/
printf("ret = %d\n",ret);
}
return 0;
}
可以看出此時函數指針數組大大減少了代碼的長度。
本文出自 “痕跡” 博客,請務必保留此出處http://wpfbcr.blog.51cto.com/10696766/1708362