【c语言】使用NULL和指针来寻找数组中是否存在指定的数字

#include<stdio.h>
#include<math.h>
void main(){
    int a[5],i,*p;
    int x=10;
    srand(time());
    printf("input data to array:\n");
    for(i=0;i<5;i++){
        a[i]=rand()%100;
        printf("%-4d",a[i]);
    }
        printf("\n");
    p=NULL;
    for(i=0;i<5;i++){
        if(a[i]==x){
            p=&a[i];
        }
    }
    if(p!=NULL){
        printf("the %d address is %x\n",x,p);
    }
    else{
            printf("the %d not in array\n",x);
    }
    printf("\n");

}

备注:指针如果不让它等于NULL,它永远都会指向一个地址。所以先让它为NULL,如果找到了就输出要找的数的地址,找不到,就是NULL,返还else里的内容。

posted on 2014-12-21 21:57  蜘蛛牛牛  阅读(473)  评论(0编辑  收藏  举报

导航