c语言指针接收数组的值(C数组指针函数指针做函数参数和返回值)
数组和函数不能用做参数和返回值,但数组指针和函数指针可以,我来为大家科普一下关于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-
,免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com