我目前正在我的初学者编程课程项目中工作,在其中必须对结构数组进行几次搜索,例如,我具有这两种不同的结构:
typedef struct{
char name[SIZE];
int number, year, isbn;
}magazine;
typedef struct{
char title[SIZE];
char author[SIZE];
int isbn, year;
}book;
如您所见,书和杂志都将isbn作为一个共同元素,并且可以对两种数据结构都使用isbn进行查询,我的问题是,我该如何制作(或使用glibc)通用的函数目的,而不必这样做:
book *search_book(book *array, int key){
//We search a book by its isbn and return the pointer.
}
magazine *search_mag(magazine *array, int key){
//We search a magazine by its isbn and return the pointer
}
并且能够在单个函数中搜索两个数据结构?
[您可能考虑使用这样的结构并编写一个函数来检查类型,然后调用一个知道如何搜索书籍和杂志的专用函数之一。
typedef enum { INVALID, BOOK, MAGAZINE } itemType;
typedef struct {
union {
book b;
magazine m;
} u;
itemType type;
} Item;
该函数可能看起来像这样:
Item *search(Item *array, int key){
Item * result = NULL;
...
switch (array[i].type)
{
case BOOK: result = < do book search here >
break;
case MAGAZINE: result = < do magazine search here >
break;
default: // handle invalid case here
break;
}
...
return result;
}
这是C ++模板非常适合的地方。但是,在纯C语言中,这是个地狱:首先,您需要为数组指定一个通用类型,该类型可能是void*
,但这也会删除所有类型信息。因此,您的搜索功能还需要知道一个元素的大小以及isbn
成员中一个元素内部的偏移量。]
这是指针算术开始发挥作用的地方,毫无疑问,您什么都不要做。如果您想这样做,请查看sizeof
以及C语言中常用的offsetof
宏,但我确实认为这是相当高级的。