结构的访问元素传递给一个void *指针 [英] access element of struct passed into a void* pointer
问题描述
我用二叉搜索树数据结构的工作进行排序的类型定义了一系列结构的:
I'm working with a binary search tree data structure to sort a series of structs with the type definitions:
typedef struct {
char c;
int index;
} data_t;
typedef struct node node_t;
typedef node {
void *data;
node_t *left;
node_t *right;
}
的node_t类型定义是从提供给我为此目的,presumably与一个void *指针,以确保多态性的库。 节点
将传递到函数:
静态无效
* recursive_search_tree(node_t *根,
无效*键,INT CMP(void *的,无效*))
在recursive_search_tree功能,我希望能够修改code使用索引元素为条件找到匹配最接近线性传递的索引在一个字符数组,这将最终涉及一个data_t被传递到 *键
和键盘方式>指数
在函数中被访问
Within the recursive_search_tree function, I want to be able to modify the code to use the index element as a condition to find the match closest to the index of the linear pass over an array of characters, which would ultimately involve a data_t being passed into *key
and key->index
being accessed within the function.
问题
是否有可能访问键盘>指数
,其中关键的是无效*
指向 data_t
结构或将这只可能,如果 data_t
被宣布为key的类型?我试图做后者,但是,即使铸造指向int似乎不通过编译器。
Is it possible to access key->index
where key is a void*
pointing to a data_t
struct, or would this only be possible if data_t
was declared as the type for key? I have tried to do the latter, however even casting the pointer to an int doesn't seem to pass the compiler.
推荐答案
当然这是可能的,你会投键
类型 * data_t
。 (只要这真的是键
点!)
Sure it's possible, you'd cast key
as type *data_t
. (As long as that's really what key
points to!)
key /* argument of type void* */
(data_t*)key /* cast as type data_t* */
((data_t*)key)->index /* dereferenced */
下面是一个简单的例子:
Here is a simple example:
#include <stdlib.h>
#include <stdio.h>
typedef struct {
char c;
int index;
} data_t;
typedef struct node {
void *data;
struct node *left;
struct node *right;
} node_t;
static int cmp(void *lhs, void *rhs)
{
return ((data_t *)lhs)->index - ((data_t *)rhs)->index;
}
int main(void)
{
data_t d0;
data_t d1;
d0.c = 'A';
d0.index = 1;
d1.c = 'B';
d1.index = 2;
printf("d0 < d1? %s\n", (cmp((void *)&d0, (void *)&d1) < 0 ? "yes" : "no"));
printf("d1 < d0? %s\n", (cmp((void *)&d1, (void *)&d0) < 0 ? "yes" : "no"));
return EXIT_SUCCESS;
}
这篇关于结构的访问元素传递给一个void *指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!