我有2个结构
typedef struct
{
unsigned short id;
char name[10];
char email[10];
} foo;
typedef struct
{
unsigned short id;
char test[10];
float ok;
} bar;
并且我需要创建一个可重用的函数/过程,以在这些结构的两个数组中搜索值.
这是我的功能:
short search_array(const int *array, const int dim, int query)
{
short idx = -1;
if (query >= 0)
{
for (int i = 0; i < dim; i++)
{
/*
* since array is a generic pointer,
* take:
* pointer to the position array+ i
* convert the value to unsigned short
* finally get final value of short
*/
if ((*(unsigned short *) (array + i)) == query)
{
idx = i;
i = dim;
}
}
}
return idx;
}
这是我的主要内容:
int main()
{
foo a = {10, "ok", "pippo"};
foo b = {50, "si", "gino"};
foo c = {30, "si", "peppo"};
foo foos[3] = {a, b, c};
bar a1 = {6, "mario", 5.5};
bar b2 = {56, "mimmo", 0};
bar c3 = {69, "maronno", 9};
bar bars[3] = {a1, b2, c3};
int x = search_array((const int *) foos, 3, 50);
int x1 = search_array((const int *) foos, 3, 9999999);
int y = search_array((const int *) bars, 3, 69);
int y1 = search_array((const int *) bars, 3, 9999999);
return 0;
}
如果我将函数的签名更改为:foo结构
short search_array(const foo *array, const int dim, int query)
并调用方法以:
int x = search_array(foos, 3, 30);
但不适用于条形结构,反之亦然.
我的目标是通过使用指针算术来创建单个函数/过程,而无需代码重复.
我认为通用类型在C中不存在,所以我认为可以使用结构的大小来使用指针算术.是否有帮助?