寻找指定元素的指针

寻找指定元素的指针
/***************************************************************************
功能:寻找指定元素的指针
日期:2014年12月7日15:47:09
********************************************************************************/
#include<stdio.h>
int search(int *pt, int n, int key)
{
	int *p;
	for (p = pt; p < pt + n; p++)
		if (*p == key)   //如果指针指向的值等于指定值,返回在数组中的位置
			return p - pt;
	return 0;
}
int *find(int *pt, int n, int key)
{
	int *p;
	for (p = pt; p < pt + n; p++)
		if (*p == key)   //如果指针指向的值等于指定值,返回地址
			return p;
	return 0;
}

int main()
{
	int a[] = {1,2,3,4,5,6,7,8,9,10,20,30,40,50,60};
	int i, key;
	int *j;
	printf("The elements of array a:\n");
	for (i = 0; i < sizeof(a) / sizeof(a[0]); i++)  //输出数组a的所有元素
		printf("%d ",a[i]);
	printf("\n The address of a[0] is :%d\n", &a[0]);
	printf("\n Please input the key number you want to search:");//输入要查找的值
	scanf("%d",&key);
	i = search(a, sizeof(a) / sizeof(a[0]),key);
	printf("\n The label number of key number %d in the array is :%d",key, i);//输出查找值在数组中的位置
	j = find(a, sizeof(a)/sizeof(a[0]), key);
	printf("\n The point value of the key number %d in the array is:%d\n",key ,j);//输出查找值所在位置
	return 0;
}
/***************************************************************************
The elements of array a:
1 2 3 4 5 6 7 8 9 10 20 30 40 50 60
 The address of a[0] is :1638156

 Please input the key number you want to search:4

 The label number of key number 4 in the array is :3
 The point value of the key number 4 in the array is:1638168
Press any key to continue

********************************************************************************/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值