bsearch with array of pointer of structs

740 Views Asked by At

I have a struct:

typedef struct entry_t {
  char * name;
  int lines [MAX];
  int n;/*n lines*/
} entry_t;

and a array of structs entry_t * list[MAX];

I try to use bsearch to get an entry if one exists in my following function:

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 );
}

My db log

DB argc main
DB argv main
DB printf argc
DB printf argv
DB printf argc
DB printf argv
DB printf printf
0M:

The strange thing is, that sentry isn't null, but the name is something strange(random memory location).

Thx

1

There are 1 best solutions below

2
On BEST ANSWER

sentry (when used for receiving result of bsearch()) must be of type struct entry_t **.