编程例子:通过交易码获取交易名称(待解决)

1.通过结构数组解决

A1:
#include<stdio.h> #include<stdlib.h> #include<string.h> #define MIX_SIZE 4 struct tag { char code[8]; char jymc[100]; }tags[MIX_SIZE]={ {"1000","name1"}, {"1001","name2"}, {"1002","name3"}, {"1003","name4"} }; char *getname(char *code) { int i; for(i=0;i<MIX_SIZE;i++) { if(strcmp(tags[i].code,code)==0) { return tags[i].jymc; } } return NULL; } int main() { char code[]="1000",name[100],*p; p=getname(code); printf("name=%s\n",p); exit(1); }

 在上面的基础上改了一点点,用指针指向tag结构体,不知怎么就不行了,等下班后再查明原因

A2:
#include<stdio.h> #include<stdlib.h> #include<string.h> struct tag { char code[8]; char jymc[100]; }tags[]={ {"1000","name1"}, {"1001","name2"}, {"1002","name3"}, {"1003","name4"}, {NULL,NULL} }; char *getname(char *code) { int i; struct tag *p=tags; while(p->code!=NULL) { if(strcmp(p->code,code)==0) { return p->jymc; } printf("test %s\n",p->code); p++; } return NULL; } int main() { char code[]="1010",name[100],*p; p=getname(code); if(p!=NULL) { printf("name=%s\n",p); } exit(1); } 运行结果: [root@localhost program]# ./a.o test 1000 test 1001 test 1002 test 1003 test test test test test test test test test test test test test test test test test Segmentation fault (core dumped)

 再稍微修改了一下,又可以了,与A2不同的是最后一个元素修改成一个指定字符串判定数组结束

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct tag
{
    char code[8];
    char jymc[100];
}tags[]={
                                            {"1000","name1"},
                                            {"1001","name2"},
                                            {"1002","name3"},
                                            {"1003","name4"},
                                            {"EOF",NULL}
                 };
                                    
char *getname(char *code)
{
    int i;
    struct tag *p=tags;
    while(strcmp(p->code,"EOF")!=0)
    {
        if(strcmp(p->code,code)==0)
        {
                return p->jymc;
        }
        p++;
    }
    return NULL;
}
int main()
{ 
    char code[]="1010",name[100],*p;                                    
    p=getname(code);
    
    if(p!=NULL)
        printf("name=%s\n",p);
    else 
        printf("not found \n");
        
    exit(1);
}                                    

 

 

2.通过三维数组解决,下班后再补上

posted @ 2017-05-12 09:37  东篱闲菊  阅读(305)  评论(0编辑  收藏  举报