【发布时间】:2018-04-10 04:53:13
【问题描述】:
所以我有两个函数做同样的事情,但在不同类型的变量上。
当给定int arr[] 参数时,第一个函数填充整数数组。
当给定结构作为参数时,第二个函数也用整数填充链表。
链表参数的结构看起来像这样
typedef struct {node_t *head;int size;}
list_t;
现在我已经为这两个函数实现了一个函数指针表:
typedef struct{
char *name; //name of the function
void (*fill)(int arr[]); //fill up the array
} alg_t;
alg_t algs[] = {
{"func1",fill_up_arr},
{"func2",fill_up_linkedList}
};
请注意,在保存我的指针的结构内部,填充函数指针
将int arr[] 作为参数。
我只想要该结构中的一个函数指针,有什么方法可以使用
类型转换,以便 fill_up_linkedList 等其他函数需要参数类型为 list_t 而不是 int arr[]?
//This is what I want my main to look like.
//I want func.fill to be called only once thus
//dynamically perform the operations for all functions inside the table of
//functions array
int arr = malloc(sizeof(int)algs.size);
for(int i = 0; i<algs.size;i++){
alg_t func = algs[i];
func.fill(arr);
}
似乎这段代码的问题在于循环会尝试执行fill_up_LinkedList 函数,因为它需要不同的参数。
在这种情况下如何使用类型转换?
谢谢
【问题讨论】:
-
funcs_t algs[]?你的意思是alg_t algs[]对吗? -
是的,谢谢。刚刚编辑过
-
如果您使用相同的输入 (
arr) 调用列表中的所有函数,那么所有函数都将具有相同的参数类型,所以这里没有问题。 -
会有一个问题,因为 fillUp_linked_list 采用不同的参数。它将寻找一个结构,但它会找到一个 int arr[]
-
"我只想要该结构中的一个函数指针," 你的意思是要删除
name只留下函数指针吗?如果你想调用两个单独的函数,你将需要 2 指针,除非你用union做一些事情,就像下面的 @Matthias 建议的那样。 (那么你必须手动控制哪个是最后分配的指针)
标签: c casting function-pointers typedef