c语言数组搜索,c在通用类型数组中搜索

我有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中不存在,所以我认为可以使用结构的大小来使用指针算术.是否有帮助?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值