假设我有许多C结构,我想要一组特定的函数来操作.
我想知道以下是否是合法的方法:
typedef struct Base {
int exampleMember;
// ...
} Base;
typedef struct Foo {
Base base;
// ...
} Foo;
typedef struct Bar {
Base base;
// ...
} Bar;
void MethodOperatesOnBase(void *);
void MethodOperatesOnBase(void * obj)
{
Base * base = obj;
base->exampleMember++;
}
Run Code Online (Sandbox Code Playgroud)
在示例中,您将注意到两个结构Foo并Bar以Base成员开头.
而且,在MethodOperatesOnBase那里,我将void *参数转换为Base *.
我想传递指针Bar和指向Foo此方法的指针,并依赖结构的第一个成员作为Base结构.
这是可以接受的,还是有一些(可能是编译器特定的)问题需要注意?(比如某种类型的打包/填充方案会改变结构的第一个成员的位置?)
c ×1