I started feeling comfortable with C and then I ran into type casting. If I have the following defined in an *.h file
我开始对C很满意,然后我就开始打字了。如果我在*中定义了以下内容。h文件
struct data {
int value;
char *label;
};
and this in another *.h file
这个在另一个*。h文件
# define TYPE void*
How do I cast the void pointer to the struct so that I can use a variable "TYPE val" that's passed into functions? For example, if I want to utilize the value that TYPE val points to, how do I cast it so that I can pass that value to another functions?
如何将void指针转换为struct,以便使用传递给函数的变量"TYPE val" ?例如,如果我想要利用val类型所指向的值,我该如何对它进行转换,以便能够将该值传递给另一个函数?
2 个解决方案
#1
20
(struct data*)pointer
will cast a pointer to void to a pointer to struct data
.
将一个指向void的指针转换为指向struct数据的指针。
#2
-1
Typecasting void pointer to a struct can be done in following
类型转换空指针到结构体可以在下面完成
void *vptr;
typedef struct data
{
/* members */
}tdata;
for this we can typecast to struct lets say u want to send this vptr as structure variable to some function
为此,我们可以将这个结构类型转换为struct假设u要将这个vptr作为结构变量发送给某个函数
then
然后
void function (tdata *);
main ()
{
/* here is your function which needs structure pointer
type casting void pointer to struct */
function((tdata *) vptr);
}
Note: we can typecast void pointer to any type, thats the main purpose of void pointers.
注意:我们可以将void指针类型转换为任何类型,这是void指针的主要目的。
#1
20
(struct data*)pointer
will cast a pointer to void to a pointer to struct data
.
将一个指向void的指针转换为指向struct数据的指针。
#2
-1
Typecasting void pointer to a struct can be done in following
类型转换空指针到结构体可以在下面完成
void *vptr;
typedef struct data
{
/* members */
}tdata;
for this we can typecast to struct lets say u want to send this vptr as structure variable to some function
为此,我们可以将这个结构类型转换为struct假设u要将这个vptr作为结构变量发送给某个函数
then
然后
void function (tdata *);
main ()
{
/* here is your function which needs structure pointer
type casting void pointer to struct */
function((tdata *) vptr);
}
Note: we can typecast void pointer to any type, thats the main purpose of void pointers.
注意:我们可以将void指针类型转换为任何类型,这是void指针的主要目的。