473,761 Members | 2,410 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Obtain sizeof struct element using offsetof()?

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
unsigned char butter;
unsigned short pear; // 16 bits on my platform
unsigned long peach; // 32 bits on my platform
};

static struct MemMap memMap;

/* <offset> is the offset of the MemMap struct element
** that this function is to write with the appropriately
** sized value pointed to by <pVal>.
*/
int writeMemMapReg( size_t offset, void *pVal)
{
int failures = 0;
size_t size = /* sizeof element at <offset> */;
unsigned char *p8Bits;
unsigned short *p16Bits;
unsigned long *p32Bits;

switch (size)
{
case 1:
p8Bits = (unsigned char *) pVal;
/* somehow write *p8Bits to memMap struct at
** <offset>.
*/
break;

case 2:
p16Bits = (unsigned short *) pVal;
/* somehow write *p16Bits to memMap struct at
** <offset>.
*/
break;

case 4:
p32Bits = (unsigned long *) pVal;
/* somehow write *p32Bits to memMap struct at
** <offset>.
*/
break;

default:
/* Error */
failures = !0;
break;
}

return failures;
}

Any help much appreciated.

--
- Mark ->
--
Nov 14 '05 #1
10 3406
Mark A. Odell wrote:
Is there a way to obtain the size of a struct element based only upon its
offset within the struct? [...]


No. Consider

struct x { char cx; };
struct y { char cy[100]; };

Here, `offsetof(struc t x, cx) == offsetof(struct y, cy)',
yet the sizes of the `cx' and `cy' elements are different.
No (legitimate) computation "based only" on the input value
zero could produce both 1 and 100 as outputs.

--
Er*********@sun .com

Nov 14 '05 #2
Eric Sosman <er*********@su n.com> wrote in
news:cj******** **@news1brm.Cen tral.Sun.COM:
Mark A. Odell wrote:
Is there a way to obtain the size of a struct element based only upon
its offset within the struct? [...]


No. Consider

struct x { char cx; };
struct y { char cy[100]; };

Here, `offsetof(struc t x, cx) == offsetof(struct y, cy)',
yet the sizes of the `cx' and `cy' elements are different.
No (legitimate) computation "based only" on the input value
zero could produce both 1 and 100 as outputs.


Of course. Thanks Eric. I guess I'll have to do some macro magic with some
built in assumptions about the struct if I want to simplify the caller's
interface.

Regards.

--
- Mark ->
--
Nov 14 '05 #3
In <Xn************ *************** *****@130.133.1 .4> "Mark A. Odell" <od*******@hotm ail.com> writes:
Is there a way to obtain the size of a struct element based only upon its
offset within the struct?
Even if you also knew the offset of the next member that would be
impossible, due to the padding between members.
I seem unable to figure out a way to do this
(short of comparing every element's offset with <offset>).
Nothing wrong with this approach.
What I would like to do is create an API something like this:


I can't imagine any practical need for that. You can also pass the
type of the value, encoded using an ad hoc convention: the caller *must*
know it. The callee now has all the information needed to know how to
access the pointed data.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #4
Eric Sosman wrote:
Mark A. Odell wrote:
Is there a way to obtain the size of a struct element based only upon its
offset within the struct? [...]


struct x { char cx; };
struct y { char cy[100]; };

[ . . . ] No (legitimate) computation "based only" on the input value
zero could produce both 1 and 100 as outputs.


That said, you can certainly calculate the size of each member of any
struct using only offsetof and sizeof:
sizeof(struct x) - offsetof(struct x, cx) == 1
sizeof(struct x) - offsetof(struct x, cy) == 100
It doesn't seem like you could gain much by doing this, though, unless
you're creating some kind of metaprogramming tool.
--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Nov 14 '05 #5
"Mark A. Odell" <od*******@hotm ail.com> wrote in message
news:Xn******** *************** *********@130.1 33.1.4...
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>
typedef unsigned char Apple_t;
typedef unsigned char Butter_t;
typedef unsigned short Pear_t;
typedef unsigned long Peach_t;

typedef struct mem_map
{
Apple_t apple;
Butter_t butter;
Pear_t pear;
Peach_t peach;
} MemMap;

typedef enum mem_map_offsets
{
MemMapApple = offsetof(MemMap ,apple),
MemMapButter = offsetof(MemMap ,butter),
MemMapPear = offsetof(MemMap ,pear),
MemMapPeach = offsetof(MemMap ,peach)
} MemMapOffsets;

static MemMap memMap;

/* <offset> is the offset of the MemMap struct element
** that this function is to write with the appropriately
** sized value pointed to by <pVal>.
*/ int writeMemMapReg( MemMapOffsets offset, void *pVal) {
int failures = 0;
switch(offset)
{
case MemMapApple:
memMap.apple = *(Apple_t *) pVal;
break;

case MemMapButter:
memMap.butter = *(Butter_t *) pVal;
break;

case MemMapPear:
memMap.pear = *(Pear_t *) pVal;
break;

case MemMapPeach:
memMap.peach = *(Peach_t *) pVal;
break;

default:
failures = 1;
}

return failures;
}

Any help much appreciated.

--
- Mark ->
--

Nov 14 '05 #6
Derrick Coetzee <dc****@moonfla re.com> wrote in message news:<cj******* ***@news-int2.gatech.edu >...
Eric Sosman wrote:
Mark A. Odell wrote:
Is there a way to obtain the size of a struct element based only upon its
offset within the struct? [...]


struct x { char cx; };
struct y { char cy[100]; };

[ . . . ] No (legitimate) computation "based only" on the input value
zero could produce both 1 and 100 as outputs.


That said, you can certainly calculate the size of each member of any
struct using only offsetof and sizeof:
sizeof(struct x) - offsetof(struct x, cx) == 1
sizeof(struct x) - offsetof(struct x, cy) == 100
It doesn't seem like you could gain much by doing this, though, unless
you're creating some kind of metaprogramming tool.

This is incorrect. If you have the following:

struct foo {
char cx;
char cy[100];
};

then you can have padding after cy which is included in the size
of the actual struct. so sizeof(struct foo) does not give you the
size, in bytes, of the summation of all member sizes.
Nov 14 '05 #7

"j0mbolar" <j0******@engin eer.com> wrote in message
news:2d******** *************** ***@posting.goo gle.com...
This is incorrect. If you have the following:

struct foo {
char cx;
char cy[100];
};

then you can have padding after cy which is included in the size
of the actual struct. so sizeof(struct foo) does not give you the


Practically, there are no chances to have any paddings with this code.

Instead, the following:

struct foo {
int i;
char c;
};

certainly will have the tail one.
Nov 14 '05 #8
In <cj**********@n ews-int2.gatech.edu > Derrick Coetzee <dc****@moonfla re.com> writes:
Eric Sosman wrote:
Mark A. Odell wrote:
Is there a way to obtain the size of a struct element based only upon its
offset within the struct? [...]
struct x { char cx; };
struct y { char cy[100]; };

[ . . . ] No (legitimate) computation "based only" on the input value
zero could produce both 1 and 100 as outputs.


That said, you can certainly calculate the size of each member of any
struct using only offsetof and sizeof:


Can you?
sizeof(struc t x) - offsetof(struct x, cx) == 1
sizeof(struc t x) - offsetof(struct x, cy) == 100


What about the padding the compiler can insert between any two members or
at the end?

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #9
j0mbolar wrote:
That said, you can certainly calculate the size of each member of any
struct using only offsetof and sizeof:
sizeof(stru ct x) - offsetof(struct x, cx) == 1
sizeof(stru ct x) - offsetof(struct x, cy) == 100
It doesn't seem like you could gain much by doing this, though, unless
you're creating some kind of metaprogramming tool.


This is incorrect. [ . . . ] you can have padding after cy which is included in the size
of the actual struct.


I'm sorry, of course you're right. If you have an instance of the struct
handy, though, you can always use sizeof directly on the elements:

struct x {
int a;
char b;
};

int main() {
struct x y;
int c = sizeof(y.a);
int d = sizeof(y.b);
}

--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Nov 14 '05 #10

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

Similar topics

19
9235
by: Martin Pohlack | last post by:
Hi, I have a funtion which shall compute the amount for a later malloc. In this function I need the sizes of some struct members without having an instance or pointer of the struct. As "sizeof(int)" is legal I assumed "sizeof(struct x.y)" to be legal too. But is is not: #include <dirent.h>
3
2865
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
32
2591
by: Abhishek Srivastava | last post by:
Hi, Somebody recently asked me to implement the sizeof operator, i.e. to write a function that accepts a parameter of any type, and without using the sizeof operator, should be able to return the size occupied by that datatype in memory in bytes. Thanks :) Abhishek Srivastava
9
3118
by: edson | last post by:
Greetings For certain operations I would like to have easy access to struct members. Here is an example. struct mystruct { char member1; char member1; char member1; };
6
6022
by: Urs Thuermann | last post by:
With offsetof() I can get the offset of a member in a struct. AFAICS, it is portable and clean to use this offset to access that member. I need to do something like this struct foo { struct foo *next; int a; int b; int c; };
18
2189
by: lovecreatesbea... | last post by:
1. The following code snippet uses minus operation on two pointers to calculate the distance between struct members. This is illegal, right? 2. s1 and s2 are type of the same struct S. Can the distance of s1.i4 between i3 be used to deduce the distance between s2.i4 and s2.i3? Thank you for your time. #include <stdio.h>
8
1608
by: Roman Mashak | last post by:
Hello, I already asked about my problem and received several valuable advices which I have followed to. Anyway I should explain briefly. In the program I'm working on I receive a data stream, having structure as follows: | common_header | I2C_header | data ... |
14
2795
by: ManicQin | last post by:
Hi all. I'm trying to get the size of a variable in a struct by his relative postion i.e. /// #define offsetof(s,m) (size_t)&(((s *)0)->m) struct ThePimp{ char rings; char blings;
2
3577
by: Kenneth Bull | last post by:
Say, struct foo { int x; double y; /* etc. more variables defined */ short u; char z; } a;
0
9522
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
9336
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
10111
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...
0
9948
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9765
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8770
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
7327
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...
3
3446
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2738
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.