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.
And, that in MethodOperatesOnBase
, I cast the void *
parameter to Base *
.
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?)
Example: Access members using Pointer To access members of a structure using pointers, we use the -> operator. In this example, the address of person1 is stored in the personPtr pointer using personPtr = &person1; . Now, you can access the members of person1 using the personPtr pointer.
The declaration of a structure pointer is similar to the declaration of the structure variable. So, we can declare the structure pointer and variable inside and outside of the main() function. To declare a pointer variable in C, we use the asterisk (*) symbol before the variable's name.
A structure containing a pointer to itself is not a problem. A pointer has a fixed size, so it doesn't matter how big the size of the structure it points to is. On most systems you're likely to come across, a pointer will be either 4 bytes or 8 bytes in size.
Yes, a simple exp is the link list.
Yes, the C standard specifically guarantees that this will work.
(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.")
The whole gtk+ is implemented like that. I cannot think of a better example. Take a look at http://git.gnome.org/browse/gtk+/tree/gtk/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With