LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   index of an element in the array ? (https://www.linuxquestions.org/questions/programming-9/index-of-an-element-in-the-array-366549/)

thelonius 09-24-2005 09:54 AM

index of an element in the array ?
 
Hello,

is it (and how is it) possible in C to get the index of an element in the array ? for example, with the 'bsearch' function.

Thanks

well, i think the solution is quite simple:

Code:

int get_index( type element, type* array, int arraysize) {
  type *buffer;
  buffer = bsearch( &element, array, arraysize, sizeof( type), compare);
  if( buffer == NULL)
    return -1;
  return ((long) buffer - (long) array) / sizeof( type);
}

int compare( void* first, void* second) {
  if( (type*) first == (type*) second)
    return 0;
  ...
}


acid_kewpie 09-24-2005 12:41 PM

I assume this is no longer an open question then...


All times are GMT -5. The time now is 09:13 PM.