c - c中的通用数据结构搜索

标签 c generics data-structures structure

我正在尝试用 c 编写一个完全通用的数据结构库。
在 c 编程中是否有任何方法或技术允许在不知道数据类型的情况下搜索数据?
在这里,我必须根据我的数据类型再次定义我的比较函数。

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

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

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

我想知道在 c 或任何其他技术中是否有比较元素“结构、 union 、数组”的常见方法。

最佳答案

在不知道数据类型的情况下无法比较两个对象。

第一次尝试可能是使用类似memcmp 的东西,但至少有以下三个原因导致失败:

  1. 不知道类型,就不知道对象的大小。
  2. 即使您可以通过某种方式得出一些大小,比较 structunion 类型的对象也可能会由于填充而导致错误的结果。
  3. 基于内存布局的比较最多只能实现“浅”比较,就各自的数据类型而言可能不代表“相等”。

所以唯一的方法(这是由通用库使用的)是定义接受用户定义的比较函数作为参数的函数。

关于c - c中的通用数据结构搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49037421/

相关文章:

c# - 返回未知数据类型

java - 如何调用参数化类型的方法?

dictionary - Clojure - 沿着路径行走

c - 如何在 C 中运行计时器

c - 使用 beaglebone Black SPI 在 DIP203-6 LCD 屏幕上显示字符

c - 如何在完全下载之前丢弃数据包

c - 普通 C 中类型安全的通用数据结构?

c - 将函数指针设置为静态地址

swift - 是否可以向 Swift 协议(protocol)一致性扩展添加类型约束?

data-structures - 通用哈希的基础知识,如何确保可访问性