Click to See Complete Forum and Search --> : find offset fo struct member
vijay.yande
July 2nd, 2008, 06:35 AM
How to find offset of struct member
struct
{
int a;
char b[30];
double d;
}
how to find at what possition does b starts or d starts. There is macro offsetof but that is not quite useful if you dont have struct available ie offsetof is not useful foe me. Please give any other way to to find offset.
Problem here is coming because of struct padding and alignment.
Hope you get it..!!
Dave1024
July 2nd, 2008, 07:36 AM
Expect offset in the form of memory address then just check the following logic
struct
{
int a;
char b[30];
double d;
}mem; // Create a structure variable
use the '&' operator just take the starting location. Pointing to the starting location and properly manage the offset
int *p;
char *q;
double *d;
p = & mem.a;
q = mem.b;
d = &mem.d;
ok want to access the 10th character of array b then do the follwing
q = q + 10
The single dimensional array allocation done by blocks so here a block of size 30 is allocated.if block with size 28 is available then allocation fail. show run time error
DreamShore
July 2nd, 2008, 08:23 AM
When the sturcture is not available how could anyone know the offests of its members? They don't even exist. One way is give the structure a name. The other way is to force the alignment, but not recommended though.
To Dave1024,
you can just write &mem.b + 10 or &mem.b[10].
-
And I don't quite get what you mean by block. On 32-bit system The "mem" actually takes 48 bytes, offset of a is 0, b is 4, d is 40 (not 34), and d takes 8.
a1ex07
July 2nd, 2008, 11:53 AM
If you need something that works as offsetof for anonymous structures you can use the following
struct
{
int a;
char b[30];
double d;
} mystruct;
....
size_t offset_d = size_t(reinterpret_cast<uintptr_t>(&mystruct.d) -
reinterpret_cast<uintptr_t>(&mystruct));
size_t offset_b = reinterpret_cast<uintptr_t>(&mystruct.b) -
reinterpret_cast<uintptr_t>(&mystruct);
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.