寻找指定元素的指针
/***************************************************************************
功能:寻找指定元素的指针
日期: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
********************************************************************************/