传递结构的字段名称以在函数内部访问 [英] Pass the field name of struct to access inside a function
本文介绍了传递结构的字段名称以在函数内部访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个链表,我做了一个函数来获取一个节点.但我想同时使用它来按名字或姓氏进行搜索.
I have a linked list and I made a function to fetch a node. But I want to use it both to search by first or last name.
typedef struct people {
char name[60],
lastname[60];
struct people *next;
} people;
people *search(const char *key, people *list, FIELD) {
while (list && strcmp(key, list->FIELD) != 0) {
list = list->next;
}
return list;
}
示例:
people *aux;
aux = search("John", list_of_people, "name");
或者:
aux = search("Smith", list_of_people, "lastname");
有没有一种清晰有效的方法来解决这个问题而不需要重复代码?
There is a clear and efficient way to solve this problem without repeating code?
推荐答案
use offsetof(
宏.
例如:
people *search(const char *key, people *list, size_t FIELD) {// FIELD is field offset,
while (list && strcmp(key, (char*)list + FIELD) != 0) {
list = list->next;
}
return list;
}
打电话
aux = search("John", list_of_people, offsetof(people, name));
aux = search("Smith", list_of_people, offsetof(people, lastname));
这篇关于传递结构的字段名称以在函数内部访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文