By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,482 Members | 1,611 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,482 IT Pros & Developers. It's quick & easy.

Uses of offsetof?

P: n/a
Just out of personal curiosity :)

What do people use offsetof() for? I mean, I can understand why you'd
want to be able to take the address of a member of a struct, but you
can do that with just &(s.a) or similar. Why you'd care about the
offset (which surely depends on how the compiler chooses to lay the
struct out in memory), I don't really know. And if you did really
care, won't offset(s,a) just be &(s.a) - &s ?

Mar 24 '07 #1
Share this Question
Share on Google+
24 Replies


P: n/a
On Mar 24, 12:06 am, Francine.Ne...@googlemail.com wrote:
Just out of personal curiosity :)

What do people use offsetof() for? I mean, I can understand why you'd
want to be able to take the address of a member of a struct, but you
can do that with just &(s.a) or similar. Why you'd care about the
offset (which surely depends on how the compiler chooses to lay the
struct out in memory), I don't really know. And if you did really
care, won't offset(s,a) just be &(s.a) - &s ?
Hmmm, I've been doing some experiments with this myself... The last
statement of mine seems to be false. For example, consider the
following code:

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>

#define STRING "just a test"

struct s { int a; char *b; int c; };
struct t { char *b; int c; };

main()
{
struct s a;
a.a=10, a.b=malloc(strlen(STRING)+1), strcpy(a.b,STRING), a.c=20;
struct t *b=&a.b;
struct t *c=&a+offsetof(struct s,b);
printf("%s : %d\n", b->b, b->c);
printf("%s : %d\n", c->b, c->c);
}

Now see what happens:

$ ./a.out
just a test : 20
(null) : -1208827916

So offsetof() isn't even useful for finding your way to substructures!

Mar 24 '07 #2

P: n/a
In article <11**********************@b75g2000hsg.googlegroups .com>,
<Fr************@googlemail.comwrote:
struct s a;
[...]
struct t *c=&a+offsetof(struct s,b);
Since &a is of type (struct s *), the addition is in units of the
size of s. If you do

struct t *c=((char *)&a)+offsetof(struct s,b);

you will get the answer you expect.

One use of offsetof() is to effectively pass around a member of a
structure, when *which* member it is is not known at compile time.
Instead you pass the offset of the desired member. Of course, you
also need to somehow know the type - or at least the size - of the
object you wish to manipulate.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Mar 24 '07 #3

P: n/a
Fr************@googlemail.com wrote:
Just out of personal curiosity :)

What do people use offsetof() for? I mean, I can understand why you'd
want to be able to take the address of a member of a struct, but you
can do that with just &(s.a) or similar. Why you'd care about the
offset (which surely depends on how the compiler chooses to lay the
struct out in memory), I don't really know. And if you did really
care, won't offset(s,a) just be &(s.a) - &s ?
I use offsetof() when I need to describe the position of
something within a struct to a part of the program that doesn't
have access to the struct definition. For example, I've got a
function to sort linked lists of structs, whose declaration is

void *listsort(void *listHead, size_t linkOffset,
int (*compareFunc)(const void *, const void*))

.... and which is called like

list = listsort(list, offsetof(struct node, next), comp);

This allows listsort() to handle lists of any kind of struct,
no matter where in the struct the `next' pointer is located.

The need for "layout-blindness" arises in other contexts, too,
and whenever it does offsetof() is likely to show up.

--
Eric Sosman
es*****@acm-dot-org.invalid

Mar 24 '07 #4

P: n/a
On Mar 24, 12:50 pm, rich...@cogsci.ed.ac.uk (Richard Tobin) wrote:
In article <1174738267.585150.155...@b75g2000hsg.googlegroups .com>,

<Francine.Ne...@googlemail.comwrote:
struct s a;
[...]
struct t *c=&a+offsetof(struct s,b);

Since &a is of type (struct s *), the addition is in units of the
size of s. If you do

struct t *c=((char *)&a)+offsetof(struct s,b);

you will get the answer you expect.
Ahh, I see, thanks.
One use of offsetof() is to effectively pass around a member of a
structure, when *which* member it is is not known at compile time.
Instead you pass the offset of the desired member. Of course, you
also need to somehow know the type - or at least the size - of the
object you wish to manipulate.
I guess that makes sense - doesn't sound like something you'd want to
do all that often though.
-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.

Mar 24 '07 #5

P: n/a
On Sat, 24 Mar 2007 09:22:39 -0400, Eric Sosman
<es*****@acm-dot-org.invalidwrote:
>Fr************@googlemail.com wrote:
>Just out of personal curiosity :)

What do people use offsetof() for? I mean, I can understand why you'd
want to be able to take the address of a member of a struct, but you
can do that with just &(s.a) or similar. Why you'd care about the
offset (which surely depends on how the compiler chooses to lay the
struct out in memory), I don't really know. And if you did really
care, won't offset(s,a) just be &(s.a) - &s ?

I use offsetof() when I need to describe the position of
something within a struct to a part of the program that doesn't
have access to the struct definition. For example, I've got a
function to sort linked lists of structs, whose declaration is

void *listsort(void *listHead, size_t linkOffset,
int (*compareFunc)(const void *, const void*))

... and which is called like

list = listsort(list, offsetof(struct node, next), comp);
I don't think the question is about the usefulness of the value but
the need for the macro when the expressions
(char*)&structure.member - (char*)&structure
or
(char*)(&struct_ptr->member) - (char*)struct_ptr
will provide the value without the macro.

Remove del for email
Mar 24 '07 #6

P: n/a
On 24 Mar 2007 05:11:07 -0700, Fr************@googlemail.com wrote:
>On Mar 24, 12:06 am, Francine.Ne...@googlemail.com wrote:
>Just out of personal curiosity :)

What do people use offsetof() for? I mean, I can understand why you'd
want to be able to take the address of a member of a struct, but you
can do that with just &(s.a) or similar. Why you'd care about the
offset (which surely depends on how the compiler chooses to lay the
struct out in memory), I don't really know. And if you did really
care, won't offset(s,a) just be &(s.a) - &s ?

Hmmm, I've been doing some experiments with this myself... The last
statement of mine seems to be false. For example, consider the
following code:

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>

#define STRING "just a test"

struct s { int a; char *b; int c; };
struct t { char *b; int c; };

main()
{
struct s a;
a.a=10, a.b=malloc(strlen(STRING)+1), strcpy(a.b,STRING), a.c=20;
struct t *b=&a.b;
Didn't your compiler issue a diagnostic about incompatible pointer
types? &a.b is a char**. b is a struct t*. There is no implicit
conversion between them.

Unless you have a C99 compiler, you need to put your declarations
before your statements.
struct t *c=&a+offsetof(struct s,b);
What makes you think that the internal structure of a struct t is the
same as the internal structure of the last two members of of a struct
s. The compiler is allowed to insert padding between the 2nd and 3rd
members of a struct s while not doing so between the 1st and 2nd
members of a struct t. It is also allowed to do the reverse. It is
also allowed to insert padding in both structures but the the amount
of padding could be different between the two.
printf("%s : %d\n", b->b, b->c);
printf("%s : %d\n", c->b, c->c);
}

Now see what happens:

$ ./a.out
just a test : 20
(null) : -1208827916

So offsetof() isn't even useful for finding your way to substructures!
Not if you make unwarranted assumptions or mistakes in arithmetic
(pointed out else thread).
Remove del for email
Mar 24 '07 #7

P: n/a
Fr************@googlemail.com wrote:
On Mar 24, 12:06 am, Francine.Ne...@googlemail.com wrote:
>Just out of personal curiosity :)

What do people use offsetof() for? I mean, I can understand why you'd
want to be able to take the address of a member of a struct, but you
can do that with just &(s.a) or similar. Why you'd care about the
offset (which surely depends on how the compiler chooses to lay the
struct out in memory), I don't really know. And if you did really
care, won't offset(s,a) just be &(s.a) - &s ?

Hmmm, I've been doing some experiments with this myself... The last
statement of mine seems to be false. For example, consider the
following code:
Your code includes two illegal initializations and an example of
erroneous pointer addition. Try this:

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>

#define STRING "just a test"

struct s
{
int a;
char *b;
int c;
};
struct t
{
char *b;
int c;
};

int main(void)
{
struct s a;
a.a = 10, a.b =
malloc(strlen(STRING) + 1), strcpy(a.b, STRING), a.c = 20;
#if 0
/* mha: the following are illegal initializationa */
struct t *b = &a.b;
struct t *c = &a + offsetof(struct s, b);
#endif
/* mha: if you insist on playing these games, try the following, but
this is *not* recommended. Notice that your initialization of c
involves pointer addition which you do not seem to understand. */
struct t *b = (struct t *) &a.b;
struct t *c = (struct t *) ((char *) &a + offsetof(struct s, b));
printf("a: \"%s\" : %d\n", a.b, a.c);
printf("b: \"%s\" : %d\n", b->b, b->c);
printf("c: \"%s\" : %d\n", c->b, c->c);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>

#define STRING "just a test"

struct s { int a; char *b; int c; };
struct t { char *b; int c; };

main()
{
struct s a;
a.a=10, a.b=malloc(strlen(STRING)+1), strcpy(a.b,STRING), a.c=20;
struct t *b=&a.b;
struct t *c=&a+offsetof(struct s,b);
printf("%s : %d\n", b->b, b->c);
printf("%s : %d\n", c->b, c->c);
}

Now see what happens:

$ ./a.out
just a test : 20
(null) : -1208827916

So offsetof() isn't even useful for finding your way to substructures!
Your code shows no such thing. It shows that you haven't read your
textbook very well.

Mar 24 '07 #8

P: n/a
<Fr************@googlemail.comwrote in message
>
I guess that makes sense - doesn't sound like something you'd want to
do all that often though.
Let's say I've got a databse of football players
typedef struct
{
float tackling;
float shooting;
float passing;
float running;
float control;
float aggression;
float luckiness;

.. lots more.
} PLAYER;

Now one thing we are probably want to do is to trawl through that array
extracting averages for all our attributes.
The only way of doing this, short of writing a separate function for each
field, is to pass in an offset.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm
Mar 24 '07 #9

P: n/a
Malcolm McLean wrote:
<Fr************@googlemail.comwrote in message
>>
I guess that makes sense - doesn't sound like something you'd want to
do all that often though.

Let's say I've got a databse of football players
typedef struct
{
float tackling;
float shooting;
float passing;
float running;
float control;
float aggression;
float luckiness;

.. lots more.
} PLAYER;

Now one thing we are probably want to do is to trawl through that array
extracting averages for all our attributes.
The only way of doing this, short of writing a separate function for
each field, is to pass in an offset.
It's hardly the only way.

const char *attribute_names[] = {"tackling", "shooting", "passing",
"running", "control", "aggression", "luckiness"};

typedef struct
{
float attributes[sizeof attribute_names/sizeof *attribute_names];
/* other stuff, like player names which can't be in the float array */
} PLAYER;

This may be a much more usable approach, and if you include something like
enum {tackling, shooting, passing, running, control, aggression,
luckiness, no_more_attributes);
handing the attributes and their names can become very flexible, whether
you know which attibutes you are concerned with or not.

Mar 24 '07 #10

P: n/a
Barry Schwarz wrote:
On Sat, 24 Mar 2007 09:22:39 -0400, Eric Sosman
<es*****@acm-dot-org.invalidwrote:
Fr************@googlemail.com wrote:
Just out of personal curiosity :)

What do people use offsetof() for? I mean, I can understand why you'd
want to be able to take the address of a member of a struct, but you
can do that with just &(s.a) or similar. Why you'd care about the
offset (which surely depends on how the compiler chooses to lay the
struct out in memory), I don't really know. And if you did really
care, won't offset(s,a) just be &(s.a) - &s ?
I use offsetof() when I need to describe the position of
something within a struct to a part of the program that doesn't
have access to the struct definition. For example, I've got a
function to sort linked lists of structs, whose declaration is

void *listsort(void *listHead, size_t linkOffset,
int (*compareFunc)(const void *, const void*))

... and which is called like

list = listsort(list, offsetof(struct node, next), comp);

I don't think the question is about the usefulness of the value but
the need for the macro when the expressions
(char*)&structure.member - (char*)&structure
or
(char*)(&struct_ptr->member) - (char*)struct_ptr
will provide the value without the macro.
You can only calculate (char*)(&struct_ptr->member) -
(char*)struct_ptr once you have an instance of your structure.
offsetof(struct node, next) can be used anywhere. Additionally,
offsetof's result is guaranteed to be suitable for use in constant
expressions.

Mar 24 '07 #11

P: n/a

"Martin Ambuhl" <ma*****@earthlink.netwrote in message
Malcolm McLean wrote:
><Fr************@googlemail.comwrote in message
>>>
I guess that makes sense - doesn't sound like something you'd want to
do all that often though.

Let's say I've got a databse of football players
typedef struct
{
float tackling;
float shooting;
float passing;
float running;
float control;
float aggression;
float luckiness;

.. lots more.
} PLAYER;

Now one thing we are probably want to do is to trawl through that array
extracting averages for all our attributes.
The only way of doing this, short of writing a separate function for each
field, is to pass in an offset.

It's hardly the only way.

const char *attribute_names[] = {"tackling", "shooting", "passing",
"running", "control", "aggression", "luckiness"};

typedef struct
{
float attributes[sizeof attribute_names/sizeof *attribute_names];
/* other stuff, like player names which can't be in the float array */
} PLAYER;

This may be a much more usable approach, and if you include something like
enum {tackling, shooting, passing, running, control, aggression,
luckiness, no_more_attributes);
handing the attributes and their names can become very flexible, whether
you know which attibutes you are concerned with or not.
That actually is how more or less how databases solve the problem. Structs
are impractical because there is no way of knowing what fields the user will
want at compile time. However I was assuming that the player array was a
given. It was actually a real problem. We had a football mangement game, and
the attributes were used throughout the program to determine the outcome of
games, transfer values, and so forth. We also needed some generic operations
on "an attribute"

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Mar 24 '07 #12

P: n/a
On 24 Mar 2007 10:56:12 -0700, "Harald van D?k" <tr*****@gmail.com>
wrote:
>Barry Schwarz wrote:
>On Sat, 24 Mar 2007 09:22:39 -0400, Eric Sosman
<es*****@acm-dot-org.invalidwrote:
>Fr************@googlemail.com wrote:
Just out of personal curiosity :)

What do people use offsetof() for? I mean, I can understand why you'd
want to be able to take the address of a member of a struct, but you
can do that with just &(s.a) or similar. Why you'd care about the
offset (which surely depends on how the compiler chooses to lay the
struct out in memory), I don't really know. And if you did really
care, won't offset(s,a) just be &(s.a) - &s ?

I use offsetof() when I need to describe the position of
something within a struct to a part of the program that doesn't
have access to the struct definition. For example, I've got a
function to sort linked lists of structs, whose declaration is

void *listsort(void *listHead, size_t linkOffset,
int (*compareFunc)(const void *, const void*))

... and which is called like

list = listsort(list, offsetof(struct node, next), comp);

I don't think the question is about the usefulness of the value but
the need for the macro when the expressions
(char*)&structure.member - (char*)&structure
or
(char*)(&struct_ptr->member) - (char*)struct_ptr
will provide the value without the macro.

You can only calculate (char*)(&struct_ptr->member) -
(char*)struct_ptr once you have an instance of your structure.
offsetof(struct node, next) can be used anywhere. Additionally,
offsetof's result is guaranteed to be suitable for use in constant
expressions.
While it appears true enough, I don't find the first point convincing.
But the second is the best answer I have seen so far to the original
question. Thank you.
Remove del for email
Mar 24 '07 #13

P: n/a
In article <1s********************************@4ax.com>,
Barry Schwarz <sc******@doezl.netwrote:
>>struct s { int a; char *b; int c; };
struct t { char *b; int c; };
>What makes you think that the internal structure of a struct t is the
same as the internal structure of the last two members of of a struct
s. The compiler is allowed to insert padding between the 2nd and 3rd
members of a struct s while not doing so between the 1st and 2nd
members of a struct t. It is also allowed to do the reverse. It is
also allowed to insert padding in both structures but the the amount
of padding could be different between the two.
This may be theoretically true, but is unlikely in practice. Provided
you document your assumptions, it is not unreasonable - at least when
there is a good reason for it in the first place.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Mar 24 '07 #14

P: n/a

"Richard Tobin" <ri*****@cogsci.ed.ac.ukwrote in message
news:eu***********@pc-news.cogsci.ed.ac.uk...
In article <1s********************************@4ax.com>,
Barry Schwarz <sc******@doezl.netwrote:
>>>struct s { int a; char *b; int c; };
struct t { char *b; int c; };
>>What makes you think that the internal structure of a struct t is the
same as the internal structure of the last two members of of a struct
s. The compiler is allowed to insert padding between the 2nd and 3rd
members of a struct s while not doing so between the 1st and 2nd
members of a struct t. It is also allowed to do the reverse. It is
also allowed to insert padding in both structures but the the amount
of padding could be different between the two.

This may be theoretically true, but is unlikely in practice. Provided
you document your assumptions, it is not unreasonable - at least when
there is a good reason for it in the first place.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Certainly you're joking. ( Mr. Feynman.)
Mar 24 '07 #15

P: n/a
Eric Sosman wrote:
Fr************@googlemail.com wrote:
>Just out of personal curiosity :)

What do people use offsetof() for? I mean, I can understand why
you'd want to be able to take the address of a member of a struct,
but you can do that with just &(s.a) or similar. Why you'd care
about the offset (which surely depends on how the compiler chooses
to lay the struct out in memory), I don't really know. And if you
did really care, won't offset(s,a) just be &(s.a) - &s ?

I use offsetof() when I need to describe the position of
something within a struct to a part of the program that doesn't
have access to the struct definition. For example, I've got a
function to sort linked lists of structs, whose declaration is

void *listsort(void *listHead, size_t linkOffset,
int (*compareFunc)(const void *, const void*))

... and which is called like

list = listsort(list, offsetof(struct node, next), comp);

This allows listsort() to handle lists of any kind of struct,
no matter where in the struct the `next' pointer is located.

The need for "layout-blindness" arises in other contexts,
too, and whenever it does offsetof() is likely to show up.
Similarly I use it in nmalloc to make the internal structure
visible to debugging code, with dynamic adjustment of that code. I
can change the actual structure definitions in nmalloc freely
without having to alter other modules. The publication is via a
name containing a leading _, and thus supposed to be inaccessible
to non-system code. See download section on my page.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Mar 24 '07 #16

P: n/a
On Mar 24, 5:34 pm, Barry Schwarz <schwa...@doezl.netwrote:
What makes you think that the internal structure of a struct t is the
same as the internal structure of the last two members of of a struct
s. The compiler is allowed to insert padding between the 2nd and 3rd
members of a struct s while not doing so between the 1st and 2nd
members of a struct t. It is also allowed to do the reverse. It is
also allowed to insert padding in both structures but the the amount
of padding could be different between the two.
So how do you portably cast to a substruct then?
printf("%s : %d\n", b->b, b->c);
printf("%s : %d\n", c->b, c->c);
}
Now see what happens:
$ ./a.out
just a test : 20
(null) : -1208827916
So offsetof() isn't even useful for finding your way to substructures!

Not if you make unwarranted assumptions or mistakes in arithmetic
(pointed out else thread).

Remove del for email

Mar 25 '07 #17

P: n/a
>On Mar 24, 5:34 pm, Barry Schwarz <schwa...@doezl.netwrote:
>What makes you think that the internal structure of a struct t is the
same as the internal structure of the last two members of of a struct
s. ...
In article <11**********************@p77g2000hsh.googlegroups .com>
<Fr************@googlemail.comwrote:
>So how do you portably cast to a substruct then?
"You don't!" :-)

If you want a structure "t" that contains a sub-structure "s",
just include an actual "s" inside the "t":

struct S { ... whatever goes here ... };
struct T {
/* stuff before the S */
struct S s;
/* stuff after the S */
};

Then the sub-structure is just, e.g.:

struct T tmp;
...
operate(&tmp.s);

It is, of course, true that it is a bit less convenient to
write "tmp.s.field" everywhere you "want" to write "tmp.field".
If you prefer the more convenient version, you have at least
two options:

- Use C++, which has "inheritance"; or
- Use Plan 9 C, which has anonymous members.

Plan 9 C's anonymous members give you much of the functionality
of C++ (single) inheritance, with very little mechanism (though
of course there is no multiple inheritance, which eliminates the
"diamond problem").
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (4039.22'N, 11150.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Mar 25 '07 #18

P: n/a
<Fr************@googlemail.comwrote in message
news:11**********************@p77g2000hsh.googlegr oups.com...
On Mar 24, 5:34 pm, Barry Schwarz <schwa...@doezl.netwrote:
>What makes you think that the internal structure of a struct t is the
same as the internal structure of the last two members of of a
struct s. The compiler is allowed to insert padding between the
2nd and 3rd members of a struct s while not doing so between
the 1st and 2nd members of a struct t. It is also allowed to do the
reverse. It is also allowed to insert padding in both structures but
the the amount of padding could be different between the two.

So how do you portably cast to a substruct then?
The only sensible meaning of "substruct", given the flexibility C allows
implementations, is "a struct within a struct". Merely having the same list
of element types does not a struct make.
struct s { int a; char *b; int c; };
struct t { char *b; int c; };
....
struct s a;
struct t *b=&a.b;
This is just plain wrong; I'm surprised your compiler didn't complain when
you implicitly converted a pointer-to-pointer-to-char to a
pointer-to-struct-s. This is correct:

struct t { char *b; int c; };
struct s { int a; struct t d; };
....
struct s a;
struct t *b=&a.d;

Technically this is all you're guaranteed, but on every system I'm aware of
(minus the DS9k), if the common elements begin at the start of the two
structs, they'll be laid out the same, thus the following is assumed to
work:

struct s { int a; char *b; int c; };
struct t { int a; char *b; };
....
struct s a;
struct t *b= (struct t *)&a;

But that's the _only_ case that's assumed to work without actually making
one struct a member of the other.

S

--
Stephen Sprunk "Those people who think they know everything
CCIE #3723 are a great annoyance to those of us who do."
K5SSS --Isaac Asimov
--
Posted via a free Usenet account from http://www.teranews.com

Mar 25 '07 #19

P: n/a
On Mar 25, 8:29 pm, "Stephen Sprunk" <step...@sprunk.orgwrote:
This is just plain wrong; I'm surprised your compiler didn't complain when
you implicitly converted a pointer-to-pointer-to-char to a
pointer-to-struct-s.
But I believe it's true that a pointer to a struct can be freely
converted to and from a pointer to the first element of that struct?
>
struct t { char *b; int c; };
struct s { int a; struct t d; };
...
struct s a;
struct t *b=&a.d;

Technically this is all you're guaranteed, but on every system I'm aware of
(minus the DS9k), if the common elements begin at the start of the two
structs, they'll be laid out the same, thus the following is assumed to
work:

struct s { int a; char *b; int c; };
struct t { int a; char *b; };
...
struct s a;
struct t *b= (struct t *)&a;

But that's the _only_ case that's assumed to work without actually making
one struct a member of the other.

S

--
Stephen Sprunk "Those people who think they know everything
CCIE #3723 are a great annoyance to those of us who do."
K5SSS --Isaac Asimov

--
Posted via a free Usenet account fromhttp://www.teranews.com

Mar 25 '07 #20

P: n/a
On 25 Mar 2007 15:10:52 -0700, Fr************@googlemail.com wrote in
comp.lang.c:
On Mar 25, 8:29 pm, "Stephen Sprunk" <step...@sprunk.orgwrote:
This is just plain wrong; I'm surprised your compiler didn't complain when
you implicitly converted a pointer-to-pointer-to-char to a
pointer-to-struct-s.

But I believe it's true that a pointer to a struct can be freely
converted to and from a pointer to the first element of that struct?
It can be converted, with a suitable cast. There are no automatic
conversions between pointers to objects of different types with the
exception of pointer to void. A pointer to any object type may be
converted to pointer to void without a cast, and vice-versa.

Since a structure cannot contain an instance of itself, the first
member of that struct is some other type of object. Therefore a cast
is always required to convert between a pointer to a struct and a
pointer to its first member.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
Mar 25 '07 #21

P: n/a
On Mar 24, 12:06 pm, Francine.Ne...@googlemail.com wrote:
Just out of personal curiosity :)

What do people use offsetof() for?
I use it in the table definition for a table-driven user
interface to edit members of a struct.

Mar 25 '07 #22

P: n/a
<Fr************@googlemail.comwrote in message
news:11*********************@d57g2000hsg.googlegro ups.com...
On Mar 25, 8:29 pm, "Stephen Sprunk" <step...@sprunk.orgwrote:
>This is just plain wrong; I'm surprised your compiler didn't complain
when you implicitly converted a pointer-to-pointer-to-char to a
pointer-to-struct-s.

But I believe it's true that a pointer to a struct can be freely
converted to and from a pointer to the first element of that struct?
It can be freely converted _with a cast_, but without a cast (aka an
implicit conversion) it should have generated a compiler warning. If you
didn't get a warning, you need to turn up the diagnostic level on your
compiler (e.g. "-ansi -pedantic -W -Wall" for GCC).

Also, that conversion is only guaranteed to be correct in one direction.
Converting from an int* to a pointer-to-struct whose first element is an int
is legal, but trying to access any other members of that struct invokes UB
unless your int* originated from a pointer to that struct type -- and if it
did, why didn't you just keep the pointer-to-struct around and forget the
silly casts?

S

--
Stephen Sprunk "Those people who think they know everything
CCIE #3723 are a great annoyance to those of us who do."
K5SSS --Isaac Asimov
--
Posted via a free Usenet account from http://www.teranews.com

Mar 26 '07 #23

P: n/a
Fr************@googlemail.com wrote:
Just out of personal curiosity :)

What do people use offsetof() for? I mean, I can understand why you'd
want to be able to take the address of a member of a struct, but you
can do that with just &(s.a) or similar. Why you'd care about the
offset (which surely depends on how the compiler chooses to lay the
struct out in memory), I don't really know. And if you did really
care, won't offset(s,a) just be &(s.a) - &s ?
It's used extensively inside the Linux kernel to implement
object inheritance in C.

You use offsetof to get at the parent of an object - aka
the structure which includes your current structure.

Kind regards,

Iwo

Mar 26 '07 #24

P: n/a
On Mar 25, 8:03 pm, Chris Torek <nos...@torek.netwrote:
If you want a structure "t" that contains a sub-structure "s",
just include an actual "s" inside the "t":

struct S { ... whatever goes here ... };
struct T {
/* stuff before the S */
struct S s;
/* stuff after the S */
};

Then the sub-structure is just, e.g.:

struct T tmp;
...
operate(&tmp.s);

It is, of course, true that it is a bit less convenient to
write "tmp.s.field" everywhere you "want" to write "tmp.field".
Yes, that is quite ugly :(

I suppose another alternative is to add an extra level of indirection
to all the elements of the struct, then create a little routine,
structStosubstructT, say, that creates a new T struct and populates it
with the values of the pointers to what used to be just the elements
of S. But I can imagine this would be a pain to maintain, and you'd
need a separate routine for each struct/substruct pair.
If you prefer the more convenient version, you have at least
two options:

- Use C++, which has "inheritance"; or
- Use Plan 9 C, which has anonymous members.

Plan 9 C's anonymous members give you much of the functionality
of C++ (single) inheritance, with very little mechanism (though
of course there is no multiple inheritance, which eliminates the
"diamond problem").
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (4039.22'N, 11150.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.

Mar 26 '07 #25

This discussion thread is closed

Replies have been disabled for this discussion.