Search code examples
cstructdereference

I have memory address of an struct store in int variable. Can I dereference the struct using this int value in C?


I have address of an struct store in int variable. Can I dereference the struct??

say: int x = 3432234; // memory address of struct now I want to access the some struct from it.

I have been suggest these steps.

  1. store the address in an int variable
  2. cast that int to a struct pointer
  3. then dereference it

But don't know how to apply.


Solution

  • If you have a struct foo, the easy way is to not use an int x but make the type a pointer-to-struct foo, struct foo *x. One can use the arrow operator to access members from a valid pointer directly.

    #include <stdio.h>
    
    struct foo { int a, b; };
    
    int main(void) {
        struct foo foo = { 1, 2 };
        struct foo *x = &foo;
        printf("%d, %d\n", x->a, x->b);
    }
    

    Sometimes, hardware requirements complicate this, but this is the simple solution.