c語言指針接收數組的值?數組和函數不能用做參數和返回值,但數組指針和函數指針可以,我來為大家科普一下關于c語言指針接收數組的值?下面希望有你要的答案,我們一起來看看吧!
數組和函數不能用做參數和返回值,但數組指針和函數指針可以。
1 數組指針做函數參數
數組指針做函數參數,數組名用做實參時,其形參為指向數組首元素的指針(指針目标類型為數組元素)。
#include <stdio.h>
#include <stdlib.h>
#define ROWS 3
#define COLS 2
void fun1(int (*)[COLS], int);
int main()
{
int array_2D[ROWS][COLS] = { {1, 2}, {3, 4}, {5, 6} };
int rows = ROWS;
/* works here because array_2d is still in scope and still an array */
printf("MAIN: %zu\n",sizeof(array_2D)/sizeof(array_2D[0]));
fun1(array_2D, rows);
getchar();
return EXIT_SUCCESS;
}
void fun1(int (*a)[COLS], int rows)
{
int i, j;
int n, m;
n = rows;
/* Works, because that information is passed (as "COLS").
It is also redundant because that value is known at compile time (in "COLS"). */
m = (int) (sizeof(a[0])/sizeof(a[0][0]));
/* Does not work here because the "decay" in "pointer decay" is meant
literally--information is lost. */
printf("FUN1: %zu\n",sizeof(a)/sizeof(a[0]));
for (i = 0; i < n; i ) {
for (j = 0; j < m; j ) {
printf("array[%d][%d]=%d\n", i, j, a[i][j]);
}
}
}
2 數組指針做函數返回值
數組指針做函數返回值時,數組指針是指指針目标類型為數組元素的指針。
#include <stdio.h>
#include <malloc.h>
char(*weekday())[5]
{
char(*wee)[5] = (char(*)[5])malloc(sizeof(char)*5*7);
char* str[] = {"Mon.","Tue","Wed.","Thu.","Fri.","Sat.","Sun."};
for(int i=0;i<7;i )
for(int j=0;j<5;j )
wee[i][j] = str[i][j];
return wee;
}
int main()
{
char(*week)[5] = weekday();
for(int i=0;i<7;i )
printf("%s\n",week[i]);
free(week);
setbuf(stdin,NULL);
getchar();
}
3 函數指針做函數參數
函數指針做函數參數,可以封裝函數體中因因應不同需求而需“變化”的代碼,避免“硬”編程,讓代碼更加通用和泛化。
#include <stdio.h>
void sort(int arr[],int size,bool(*comp)(int,int))
{
for(int i=0;i<size-1;i )
for(int j=0;j<size-i-1;j )
if(comp(arr[j],arr[j 1]))
{
int t = arr[j 1];
arr[j 1] = arr[j];
arr[j]=t;
}
}
bool Comp(int a,int b)
{
return a<b;
}
int main(void)
{
int arr[]={2,1,4,5,3,9,6,8,7};
int n = sizeof arr / sizeof *arr;
sort(arr,n,Comp);
for(int i=0;i<n;i )
printf("%d ",arr[i]);
getchar();
return 0;
}
4 函數指針做函數返回值
用函數返回函數指針,可以讓同類函數具有相同的接口。
#include <stdio.h>
enum Op
{
ADD = ' ',
SUB = '-',
};
int add(int a, int b)
{
return a b;
}
int sub(int a, int b)
{
return a - b;
}
/* getmath: return the appropriate math function */
int (*getmath(enum Op op))(int,int)
{
switch (op)
{
case ADD:
return &add;
case SUB:
return ⊂
default:
return NULL;
}
}
int main(void)
{
int a, b, c;
int (*fp)(int,int);
fp = getmath(ADD);
a = 1, b = 2;
c = (*fp)(a, b);
printf("%d %d = %d\n", a, b, c);
getchar();
return 0;
}
-End-
,更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!