[英]Accessing struct member variables passed into function
I have a struct stat variable named s inside a struct I defined myself as follows: 我在自己定义的结构中有一个名为s的结构状态变量,如下所示:
struct myStruct {
struct stat s;
};
and I want to find the difference between the st_mode between two myStruct objects, so my logic is to point to that struct and use a '.' 并且我想找到两个myStruct对象之间的st_mode之间的差异,因此我的逻辑是指向该结构并使用“。”。 for its member variable.
为其成员变量。
int func(const void *a, const void *b)
{
return a->s.st_mode - b->s.st_mode;
}
However, there are issues with this implementation: 但是,此实现存在一些问题:
error: request for member 's' in something not a structure or union
warning: dereferencing 'void *' pointer [enabled by default]
What do I do to correct this? 我该怎么做才能纠正这个问题?
The parameters to your function are of type const void*
not of type struct myStruct*
. 函数的参数类型为
const void*
类型,而不是struct myStruct*
类型。
Do you know for sure that they are in fact pointers to struct myStruct
s? 您是否确定它们实际上是
struct myStruct
的指针? If so you can do a cast: 如果是这样,您可以进行转换:
return ((struct myStruct*)a)->s.st_mode - ((struct myStruct*)b)->s.st_mode
but it's safer to redefine your function to only accept pointers of the correct type thus: 但是将您的函数重新定义为只接受正确类型的指针是更安全的:
int func(const struct myStruct* a, const struct myStruct* b)
and then keep the rest unchanged. 然后其余部分保持不变。
Your function should be declared as taking pointers to struct myStruct
, otherwise the compiler has no way of inferring the types of a
and b
. 应该将您的函数声明为采用指向
struct myStruct
指针,否则编译器无法推断a
和b
的类型。
int func(const struct myStruct *a, const struct myStruct *b)
{
return a->s.st_mode - b->s.st_mode;
}
Alternatively, you may use casting: 或者,您可以使用强制转换:
int func(const void *a, const void *b)
{
return (const struct myStruct*)a->s.st_mode - (const struct myStruct*)b->s.st_mode;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.