473,405 Members | 2,373 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Uses of offsetof?

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
24 3439
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
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
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
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
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
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
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
<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
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
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

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

"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
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
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
>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 (40°39.22'N, 111°50.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
<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
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
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
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
<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
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
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 (40°39.22'N, 111°50.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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Hiroki Horiuchi | last post by:
Hello. I wrote a program, but g++ warns a.c:11: warning: invalid access to non-static data member `A::y' of NULL object a.c:11: warning: (perhaps the `offsetof' macro was used incorrectly) ...
9
by: Exits Funnel | last post by:
Consider this code which is a very trimmed down version of some I've inherited and am trying to port from windows to g++: //Begin test1.cpp class foo { int i; int j; }; class bar { bar (int...
20
by: Alejo | last post by:
Hello, My implementation does not define offsetof, so I have designed a little program that 'attempts' to find the relative position of a member in its structure. It just does not work. Could...
6
by: Arthur J. O'Dwyer | last post by:
As far as I know, C89/C90 did not contain the now-standard offsetof() macro. Did C89 mandate that structs had to have a consistent layout? For example, consider the typical layout of the...
10
by: Mark A. Odell | last post by:
Is there a way to obtain the size of a struct element based only upon its offset within the struct? I seem unable to figure out a way to do this (short of comparing every element's offset with...
3
by: Michael B Allen | last post by:
Can offsetof be used to determine the offset of a member within an embedded struct member? For example, let 'struct foo' be a structure with an embedded structure 'struct bar' which has a member...
44
by: Simon Morgan | last post by:
Hi, Can somebody please help me grok the offsetof() macro? I've found an explanation on http://www.embedded.com/shared/printableArticle.jhtml?articleID=18312031 but I'm afraid it still...
8
by: Pawel | last post by:
Hallo group members. //p1.cpp #include <stdio.h> #include <linux/stddef.h> struct Person { int m_age; char* m_name; };
11
by: Kavya | last post by:
offsetof(T,m) (size_t)&(((T*)0)->m) Why do we always start from 0 in this macro to access the offset of structure or union. Does standard guarantees that structure and union reside at address 0?...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.