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.
- store the address in an int variable
- cast that int to a struct pointer
- 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.