我正在尝试用 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
的东西,但至少有以下三个原因导致失败:
- 不知道类型,就不知道对象的大小。
- 即使您可以通过某种方式得出一些大小,比较
struct
或union
类型的对象也可能会由于填充而导致错误的结果。 - 基于内存布局的比较最多只能实现“浅”比较,就各自的数据类型而言可能不代表“相等”。
所以唯一的方法(这是由通用库使用的)是定义接受用户定义的比较函数作为参数的函数。
关于c - c中的通用数据结构搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49037421/