自定义函数高级玩法:一二维数组参数传递, 指针调用函数

数组参数传递

二维数组

#include <stdio.h>//数组参数传递
void func(int (*p)[4])//二维数组
{
	int i,j;
	for (i=0;i<3;i++)
		for(j=0;j<4;j++)
		{
			printf("%d",*(*(p+i)+j));
		}
}
int main()
{
	int arr[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
	func(arr);
	return 0;
}

一维数组

#include <stdio.h>
int print(int *p)
//int print(int a[])
{	int i;
	for(i=0;i<9;i++)
		printf("%d",*(p+i));
	return 0;
}
int main()//一维数组传递
{
	int a[]={1,2,3,4,5,6,7,8,9};
	print(a);
	return 0;
}

指针调用函数

#include <stdio.h>
int add(int a,int b)
{
	int c;
	c = a + b;
	return c;
}
int main()
{
	int x,y;
	x=2;y=7;
	printf("%d",add(x,y));
	int (*p)(int,int) = &add;//定义一个函数的指针,用这个指针来指向此函数。
	//函数的返回类型 + 指针 + 函数参数类型
	printf("%d",(*p)(5,6));//使用指针来调用函数
	return 0;

}
#include <stdio.h>
int* min(int a, int b)//函数返回值为地址
{
	int c;
	if (a > b)
		{
		c = b;
		return &c;
	}
	else 
		{
		c = a;
		return &c;
	}
}
int main()
{
	int * (*p)(int,int) = min;
	int a = 1;
	int b = 2;
	printf("%d\n",*((*p)(a,b)));
	return 0;
}

字符串类型参数传递

//字符串自定义函数求字符串长度的函数
#include <stdio.h>
#include<string.h>
int len(char *p)//指针方法(char指p指向的类型是字符串,但是p本身是指针)
{
	int l = 0;
	while (*p !='\0')
	{p++;l++;}
	return l;
}
int ll(char a[])
{
	int i,len = 0;
	while (a[i]!='\0')
	{
		i++;
		len++;
	}
	return len;
}
int main()
{
	char a[] = "123456";
	char *p = a;
	printf("%d",strlen(a));
	printf("%d",len(p));
	len(p);
	ll(a[7]);
	return 0;
}

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值