我有一个结构:
typedef struct entry_t {
char * name;
int lines [MAX];
int n;/*n lines*/
} entry_t;
和一组结构entry_t * list[MAX];
如果以下函数中存在条目,我尝试使用bsearch获取条目:
int addToList(entry_t * list[], int n, const char * name, int lineNr){
int i = 0;
int j = 0;
entry_t * entry;
entry_t * sentry;
bool found = false;
char * tmp = (char*) malloc(sizeof(char)*MAX);
sentry = (entry_t *) bsearch(name,list,n,sizeof(entry_t *), cmpEntries2);
if(sentry != NULL){
printf("%s",sentry->name);
i = sentry->n;
sentry->lines[i] = lineNr;
sentry->n++;
}
else {
sentry = (entry_t *) malloc(sizeof(entry_t));
strcpy(tmp,name);
sentry->name = tmp;
sentry->lines[0] = lineNr;
sentry->n = 1;
list[n] = sentry;
n++;
}
return n;
}
int cmpEntries2(const void * a, const void * b){
assert (a != NULL);
assert (b != NULL);
printf("DB %s %s\n",(const char*)a,(*(entry_t **)b)->name );
return strcmp( (const char*)a, (*(entry_t **)b)->name );
}
我的数据库日志
DB argc main
DB argv main
DB printf argc
DB printf argv
DB printf argc
DB printf argv
DB printf printf
0M:
奇怪的是,sentry
不为空,但name
是奇怪的(随机内存位置)。
THX
答案 0 :(得分:0)
sentry
(用于接收bsearch()
的结果时)必须是struct entry_t **
类型。