在C语言中,确实指向一个结构,始终指向它的第一个成员? [英] In C, does a pointer to a structure always point to its first member?
问题描述
假设我有一些C结构为,我想一组特定的功能来操作。
Suppose I have a number of C structs for which I would like a particular set of functions to operate upon.
我想知道如果下面是一个合法的方法:
I'm wondering if the following is a legitimate approach:
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++;
}
在这个例子中你会发现,这两个结构富
和酒吧
开始以基础
成员。
In the example you'll notice that both structs Foo
and Bar
begin with a Base
member.
和,在 MethodOperatesOnBase
,我投了无效*
参数基础*
。
我想指针传递给酒吧
,以及在富
这种方法,依靠第一该结构的成员是一个基本
结构。
I'd like to pass pointers to Bar
and pointers to Foo
to this method and rely on the first member of the struct to be a Base
struct.
这是可以接受的,还是有我需要了解一些(可能是编译器特定的)问题是什么? (如某种包装/填充方案中,将改变结构的第一个成员的位置?)
Is this acceptable, or are there some (possibly compiler-specific) issues I need to be aware of? (Such as some sort of packing/padding scheme that would change the location of the first member of a struct?)
推荐答案
是的,C标准明确保证,这将正常工作。
Yes, the C standard specifically guarantees that this will work.
(C1X§6.7.2.1.13:一个指向结构对象,适当转换,道出了它的初始成员......反之有可能是内,结构对象无名填充,而不是在其开始。 。)
(C1x §6.7.2.1.13: "A pointer to a structure object, suitably converted, points to its initial member ... and vice versa. There may be unnamed padding within as structure object, but not at its beginning.")
这篇关于在C语言中,确实指向一个结构,始终指向它的第一个成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!