Home > Mobile >  I have memory address of an struct store in int variable. Can I dereference the struct using this in
I have memory address of an struct store in int variable. Can I dereference the struct using this in

Time:11-13

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.

CodePudding user response:

It is very common to use structs this way in mare metal environments as hardware registers are often memory mapped.

typedef struct
{
    volatile uint32_t reg1;
    const volatile uint32_t reg2;
}PERIPH1__t;

#define PERIPH1ADDRESS  0x56664550UL

/* OR */
uintptr_t PERIPH1ADDRESS = 0x56664550UL;

#define PERIPH1 ((PERIPH1__t *)PERIPH1ADDRESS)


 /* somewhere in the code */
PERIPH1 -> reg1 = 34;
uint32_t reg2val = PERIPH1 -> reg2;

if you want to store the address in the integer variable, the best type will be uintptr_t which is guaranteed to accommodate any pointer.

int is signed and on many systems not large enough to store addresses - for example 64 bits systems often have 64 bits addresses and only 32bits integers.

CodePudding user response:

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.

  • Related