|
-
July 2nd, 2008, 06:35 AM
#1
find offset fo struct member
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..!!
-
July 2nd, 2008, 07:36 AM
#2
Re: find offset fo struct member
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
-
July 2nd, 2008, 08:23 AM
#3
Re: find offset fo struct member
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.
Last edited by DreamShore; July 2nd, 2008 at 08:28 AM.
Nope
-
July 2nd, 2008, 11:53 AM
#4
Re: find offset fo struct member
If you need something that works as offsetof for anonymous structures you can use the following
Code:
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);
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|