I encounter a problem when I try to treat a variable value as an address and assign this value to a pointer.
Here are what I did so far.
declare and initialize two variables
uint32_t a = 0x0000000C; uint32_t b = 0x0C00000B;
initialize the pointer p = &a;
Here were the thing I tried .
p = b; doesn't work.
p = (uint32_t *)b ; doesn't work .
After compilation, there is one warning :
warning: incompatible integer to pointer conversion assigning to 'uint32_t ' (aka 'unsigned int') from 'uint32_t' (aka 'unsigned int'); take the address with & [ -wint- conversoin.
The problem is the the pointer p will be randomly assigned with some number instead 0x0C00000B
Any suggestions?
The "most correct" way convert between an integer to a pointer without any warnings, you have to cast to uintptr_t
, then to void*
, then to your pointer type.
uint32_t b = 1;
uint32_t *p = (uint32_t*)(void*)(uintptr_t)b;
But usually programmers just do macros, that are properly cast:
#define A_ADDR ((uint32_t*)0x0000000A)
#define B_ADDR ((uint32_t*)0x0000000B)
uint32_t *p = A_ADDR;
p = B_ADDR;
which compiles without a warnings on gcc -Wall -Wextra -pedantic
.
Or sometimes just macros with constant numbers, and the user is supposed to cast to (void*)
or to proper type:
#define A_ADDR 0x0000000A
#define B_ADDR 0x0000000B
uint32_t *p = (uint32_t*)A_ADDR;
p = (uint32_t*)B_ADDR;
Alternatively, if you trust your compiler, they can be static const
variables, ex. static const uint32_t *A_ADDR = (uint32_t*)0x0000000A;
I understand your problem like below.
You will store the address of a memory location in a variable and assign this to a pointer.
In your example, declare a pointer uint32_t *p; declare and initialize two variables uint32_t a = 0x0000000C; uint32_t b = 0x0C00000B;
If you want to know the value at address 0x0000000C , you need to assign a to ptr. like,
p = a; not like p = &a;
which will store the address of a in the pointer variable. which is not correct as per your problem statement.
You already have the solution - p = (uint32_t *)b ; doesn't work . The above line treats the value in variable 'b' as an address, and assigns that address to pointer 'p'. But you may get some compiler warnings. From my understanding of your use-case, p is to be used as a tracker to some location in memory. If so consider writing something similar to this, to not produce any warnings -
#define TRACKER_BASE_ADDR (0x0C00000B)
#define TRACKER_OFFSET (0x04)
uint32_t *p = TRACKER_BASE_ADDR;
// When you want to update the tracker use this
p = p + TRACKER_OFFSET;
// And when you want to read the value at tracker,
uint32_t val = *p;
Hope this helps
User contributions licensed under CC BY-SA 3.0