473,609 Members | 1,851 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3470
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(strl en(STRING)+1), strcpy(a.b,STRI NG), 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************ **********@b75g 2000hsg.googleg roups.com>,
<Fr************ @googlemail.com wrote:
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
--
"Considerat ion 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.585 150.155...@b75g 2000hsg.googleg roups.com>,

<Francine.Ne... @googlemail.com wrote:
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
--
"Considerat ion 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.invalidwrot e:
>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*)&structu re.member - (char*)&structu re
or
(char*)(&struct _ptr->member) - (char*)struct_p tr
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(strl en(STRING)+1), strcpy(a.b,STRI NG), 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(S TRING) + 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(strl en(STRING)+1), strcpy(a.b,STRI NG), 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.com wrote 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.com wrote 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_name s[] = {"tackling", "shooting", "passing",
"running", "control", "aggression ", "luckiness" };

typedef struct
{
float attributes[sizeof attribute_names/sizeof *attribute_name s];
/* 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_attribu tes);
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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
6331
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) The program is like below. class A {
9
2949
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 foo::* dataMember) :offsetof (foo, *dataMember) //Call this Line (A)
20
6454
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 I get some pointers on what I am doing wrong (apart from being coding so late at night). #include <stdlib.h>
6
2191
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 following structure: struct weird { int x; /* sizeof(int)==4 here */
10
3378
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 <offset>). What I would like to do is create an API something like this: #include <stddef.h> struct MemMap { unsigned char apple; // 8 bits on my platform
3
2857
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 'mem'. Can one do: offsetof(struct foo, bar.mem) Thanks, Mike
44
3717
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 doesn't make sense to me. The sticking point seems to be:
8
5848
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
2410
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? If yes, then what if I have two or more structures. How can they reside at same address?.
0
8139
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8091
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8579
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8232
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7024
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6064
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4098
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1686
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1403
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.