|
構造体配列でメンバごとにbsearchで検索できるようにしたいのですが、
何故か構造体の先頭のメンバしか検索できません。
例えば・・・
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct
{
char a[3];
char b[3];
int c;
} REC;
int compar(const REC *x,const REC *y)
{
return (strcmp(x->a,y->a));
}
void main(void)
{
REC x[]={
{"10","20",5},
{"30","25",15},
{"33","30",30},
{"48","42",35},
{"50","45",59},
{"92","65",77}
};
REC *p,temp;
printf("key入力==> ");
scanf("%s",temp.a);
p=bsearch(temp.a,x,6,sizeof(REC),(int (*)(const void *, const void *))compar);
if(p==NULL)
printf("該当なし\n");
else
printf("%s %s %d\n",p->a,p->b,p->c);
return;
}
↑のように構造体の先頭のメンバに対してはbsearchで検索できました。
でも今度は2番目のメンバをbsearchで検索しようとすると
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct
{
char a[3];
char b[3];
int c;
} REC;
int compar(const REC *x,const REC *y)
{
return (strcmp(x->b,y->b));
}
void main(void)
{
REC x[]={
{"10","20",5},
{"30","25",15},
{"33","30",30},
{"48","42",35},
{"50","45",59},
{"92","65",77}
};
REC *p,temp;
printf("key入力==> ");
scanf("%s",temp.b);
p=bsearch(temp.b,x,6,sizeof(REC),(int (*)(const void *, const void *))compar);
if(p==NULL)
printf("該当なし\n");
else
printf("%s %s %d\n",p->a,p->b,p->c);
return;
}
実際にkeyと該当する値があってもbsearchからはNULLが返ってきてるようで…
過去ログ等調べてみましたがそれらしきものはありませんでした。
どうすれば良いかご指摘お願いします。
|