-1

I have an array

char* m[] = {"AA", "AC", "AG", "AT", "CA", "CC", "CG", "CT", "GA", "GC", "GG", "GT", "TA", "TC", "TG", "TT"};

and Im trying to get the index of the entry that matches pseq = (char*)malloc(2);

I am just using a basic compare function right now, as I hope to create a specific one later

int compare(const void *a, const void *b)
{
        return strcmp(a, b);
}

size_t mlen = sizeof(m)/sizeof(m[0]); 

My attempt at bsearch is:

char* q = bsearch(&pseq, m, mlen, sizeof(m[0]), compare);

However, every return is NULL. But compare(pseq, m[5]) = 0 for pseq = "CC"

Tixii
  • 3
  • 1

1 Answers1

2

The pointers passed to compare are pointers to char*, so you have to dereference them to get char* that point at strings to be compared.

int compare(const void *a, const void *b)
{
        return strcmp(*(char**)a, *(char**)b);
}

Also

pseq = (char*)malloc(2);

looks bad because

  • 2-element array is too small for storing string like "CC" because there are no room to store the terminating null-character.
  • Casting results of malloc() in C is discouraged.
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • As a follow on, I am trying to use ` int pos=((int)q-(int)m[0])/sizeof(m[0]); ` to get the index of the match, but its giving me crazy big numbers. for example: q is at position 1367400520 m is at position 46039045 pos 165170184 – Tixii Feb 20 '21 at 01:48
  • Subtracting the first element `m[0]` is a bad idea. You should subtract `(int)m` instead of `(int)m[0]`. Changing the type of `q` to `char**` and subtracting the pointers directly `int pos = q - m;` is better. – MikeCAT Feb 20 '21 at 01:57
  • Thank you so much for you help! You have made my friday end on a good note !! – Tixii Feb 20 '21 at 02:11