IDEN
IDEN

Reputation: 21

Generic data structure search in c

I'm trying to code a fully generic data structure library in c.
Is there any way or technique in c programming that allows searching data without knowing its type?
Here I have to define my compare function again upon my data type.

list.h


typedef struct _node
{
   void *data;
   struct _node *next;
}NODE;

typedef struct _list
{
   NODE *head;
   NODE *tail;
   NODE *current;
}GLIST;

int search(GLIST *list,void *data,int (*COMPARE)(void*,void*));

and

list.c

int search(GLIST *list,void *data,int(*COMPARE)(void*,void*))
{
   list->current=list->head;
   int cIndex=1;
   while(list->current)
   {
       if(COMPARE(list->current->data,data))
       {
           printf("data found at position %i.\n",cIndex);
           if(list->current->next==NULL)
           {
               return 1;
           }
       }
       list->current=list->current->next;
       cIndex++;
   }
   printf("NO DATA FOUND.\n");

   return 0;
}

and

mycode.c

int compare(void *list,void *data);

typedef struct _student
{
   int studentNumber;
   char name[64];
}STUDENT;

int main()
{
  GLIST list;
  //initializing list......
  STUDENT stud;
  //code .....
  search(&list,&stud,compare) // I want an alternative of using compare here

  search(&list,&stud);     // want the function be like this and also be generic !

  return 0;
}


int compare(void *list,void *data)
{ 
    // I do not wanna have to declare this function even 
   return !strcmp(((STUDENT*)list)->name,((STUDENT*)data)->name);
}

I'm wondering if there is A COMMON thing to compare elements "structures,unions,arrays" upon it in c or any technique else.

Upvotes: 0

Views: 307

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35154

There is no way of comparing two objects without knowing their data type.

A first attempt would probably be to use something like memcmp, but this fails for at least three reasons:

  1. Without knowing the type, you do not know the size of the object.
  2. Even if you somehow could derive some size, comparing objects of type struct or union could lead to wrong result due to padding.
  3. A comparison based on the memory layout could at most achieve a "shallow" comparison, which may not represent "equality" in terms of the respective data type.

So the only way (and this is used by generic libraries) is to define functions that accept user-defined comparison functions as parameters.

Upvotes: 4

Related Questions