Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, does a pointer to a structure always point to its first member?

Tags:

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.

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?)

like image 714
Steve Avatar asked Sep 05 '11 20:09

Steve


People also ask

How do you point a pointer to a structure?

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.

How a pointer to a structure is declared in C?

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.

Can a structure have a pointer to itself?

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.

Can a structure have a pointer to itself in C?

Yes, a simple exp is the link list.


2 Answers

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.")

like image 153
hmakholm left over Monica Avatar answered Oct 04 '22 09:10

hmakholm left over Monica


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/

like image 34
debleek63 Avatar answered Oct 04 '22 08:10

debleek63