指针的使用场景实例

2016-06-28  本文已影响102人  司马捷

1.求一个字符串数组中,一个字符串的所在索引

#include <stdio.h>
#include "string.h"
#include "stdlib.h"

#define  DIM(a) (sizeof(a)/sizeof(*a))

int searchKeyTable(const char *table[],const int size,const char* key,int* pos){
    int rv =0;
    int i = 0;
    int inum = 0;
    if (table ==NULL||key == NULL || pos == NULL) {
        rv = -1;
        printf("table ==NULL||key == NULL || pos == NULL");
    }
  //  inum = (sizeof(table));//table在这里退化为一个内存指针.
    printf("inum-->%d",inum);
    for (int  i = 0; i<size; i++) {
        if (strcmp(key,table[i]) == 0) { //比较两个字符串大小 等于0表示字符串相等.
            *pos = i;
            return rv;
        }
    }
    
    /**
     *  没有找到
     */
    if (i == size) {
        *pos = -1;
    }
    return rv;
}

int main(int argc, const char * argv[]) {
    // insert code here...
    printf("Hello, World!\n");
    
 //   int inum = 0;
    int pos = 0;

    
    /**
     *  指针数组
     */
    const char *c_keyword[] = {
        "while",
        "case",
        "static",
        "do"
    };
    
    
    int result = searchKeyTable(c_keyword, DIM(c_keyword), "static", &pos);//数组作为函数参数,传递数组的长度
    if (result == 0) {
        printf("--->%d\n",pos);
    }
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读