0

I have a structure

typedef struct
{
    unsigned char status;
    unsigned char group_id;
    unsigned char acc_trip_level;
    unsigned char role[50];
    unsigned char standard_panic_header[50];
    unsigned char high_threat_message[50];
    unsigned char high_threat_header[50];
}cfg;

cfg test_val;

I'm passing this structure as an argument to a function and How can I get/access the elements of structure by memory location(in other words i want to treat this structure by memory address)

void foo(cfg *ptr)
{
    printf("%zu\n", sizeof(*ptr)); //Gives size of the strcture
    printf("%p\n", (void*)ptr); //Gives the starting address of strcure
    printf("%p\n", (void*)(ptr+4));  //I want to access the 4th element/ memorylocation
}

Is giving me the result

203
0x8049780
0x8049aac

But it should give 8048780+4 = 8048784 right.. am I missing something

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
Sorcrer
  • 1,634
  • 1
  • 14
  • 27
  • 3
    Pointer arithmetic is done in multiples of the pointee's size. Also, this is UB. – Quentin Aug 18 '15 at 15:20
  • @McKay it does in both, that's how array indexing works (`a[i]` is strictly equivalent to `*(a + i)`). – Quentin Aug 18 '15 at 15:43
  • Doing this is UB. Members of a `struct` are not always contiguous, unless you explicitly set member alignments. – Jason Aug 18 '15 at 17:31

2 Answers2

2

This works for me:

 void foo(cfg * ptr)
 {
     printf("%zu\n", sizeof(*ptr));
     printf("%p\n", ptr);
     printf("%p\n", (void *)((char *) ptr + 4));
 }

And then:

 $ ./a.out 
 203
 0x7fffb6d04ee0
 0x7fffb6d04ee4

When you used (ptr + 4) alone, you essentially got (ptr + 4 * sizeof(cfg)), because pointer arithmetic works with the size of the pointee, as someone already commented.

Also, format specifier %p should be used for addresses.

VHarisop
  • 2,816
  • 1
  • 14
  • 28
  • 1
    [you should cast pointers passed to `printf` to `void*`, too](http://stackoverflow.com/questions/7290923/when-printf-is-an-address-of-a-variable-why-use-void) – RamblingMad Aug 18 '15 at 15:46
  • @CoffeeandCode thanks for the tip, I edited my answer. – VHarisop Aug 18 '15 at 15:49
0

Try this:

void foo(cfg *ptr)
{
    printf("%zu\n",sizeof(cfg)); //Gives size of the strcture
    printf("%x\n",ptr); //Gives the starting address of strcure
    printf("%x\n",ptr->role);  //I want to access the 4th element/ memorylocation
}

If your goal is to access the internal elements of the structure by using index offsets, I recommend implementing a hash table.

Jim Fell
  • 13,750
  • 36
  • 127
  • 202