Thread: Use address offset to access struct member without losing Type, is it possible?

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    9

    Red face Iterate various type Struct member

    Hi, Gurus,

    Attempting to use variable to access struct member. Couldn't imagining it's doable by using name reference. But address offset works. The last thing has to be variable is the data type.

    Code:
    typedef struct
    {
    
    char val0;
    int val1;
    long val2;
    } TEST_STRUCT void main(void) {
    int pOffset;
    TEST_STRUCT testStruct;
    testStruct.val0 = 0xAB;
    testStruct.val1 = 0xDCBA;
    testStruct.val2 = 0xABCD
    pOffset = (void *)&testStruct.val2 - (void *)&testStruct.val0; // or use offsetof macro
    printf("0x%X.\n", *(long *)(&testStruct.val0 + pOffset); //0xABCD
    } // end of main
    Please advise a smarter way to make struct element access variable, various type for casting.

    Great thanks,
    Last edited by legendbb; 05-27-2011 at 01:08 PM. Reason: Found answer for original question.

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    So, you just want to read val2 out of the struct?
    Code:
    x = test_struct.val2;
    
    or 
    
    printf ("0x%X\n", test_struct.val2);
    Serously... you put the stuff in there with the equals sign, so you already know how to access it...

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    It's a good thing he figured it out on his own, because I have no idea what he was asking. (I was going to post about offsetof but he has that covered, so I really don't know what it is he wants.)


    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    >>Attempting to use variable to access struct member. Couldn't imagining it's doable by using name reference.

    ??? Can you elaborate?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 27
    Last Post: 04-20-2011, 07:56 PM
  2. Replies: 10
    Last Post: 09-04-2008, 01:27 PM
  3. Assigning memory address of member struct to pointer.
    By Tronic in forum C++ Programming
    Replies: 2
    Last Post: 03-20-2004, 05:53 PM
  4. "ambiguous access to class/struct/union member"
    By Mr_Jack in forum C++ Programming
    Replies: 1
    Last Post: 12-16-2003, 12:15 PM
  5. Replies: 0
    Last Post: 11-29-2002, 10:24 PM