CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jul 2008
    Posts
    5

    Smile 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..!!

  2. #2
    Join Date
    Apr 2008
    Posts
    168

    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

  3. #3
    Join Date
    May 2008
    Posts
    300

    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

  4. #4
    Join Date
    Jul 2007
    Location
    Richmond, BC
    Posts
    79

    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
  •  





Click Here to Expand Forum to Full Width

Featured