Simply use *addr
. This is valid and should always work. In case you need to get the value of the pointer instead of the value pointed to by the pointer, you will need a larger type. Typically the value of an unsigned int*
is 64 bit, while unsigned int
is only 32 bit.
C/C++: How to properly convert "unsigned int *" value to "unsigned int"?
-
10-03-2022 - |
Question
I have an "unsigned int *" value, and I need to convert it to a simple "unsigned int", so I could transfer it to a function. But, unfortunately, when I try to do a simple cast, the value gets changed:
Code:
unsigned int * addr;
...
fprintf(stdout, "=== addr: %08x ===\n", addr); fflush(stdout);
fprintf(stdout, "=== casted addr: %08x ===\n", (unsigned int)addr);
Output:
=== addr: fc880000 ===
=== casted addr: 400eff20 ===
Please tell me, how to convert this value properly, so it doesn't change during the conversion?
Solution
OTHER TIPS
When you declare a pointer, like
unsigned int * addr;
The value of that pointer will be the address of the unsigned int
it points to.
When you want to get the value of the unsigned int
it points to you use the dereference operator *
:
unsigned int value = *addr;
So what you see in the second output line is the contents of what addr
points to.
If you have a pointer of some type, and you need to convert it to just the type, you just need to deference the pointer.
void foo(unsigned int some_value);
...
int main()
{
unsigned int * addr = 0x12345678; // some address holding an unsigned int
foo(*addr); // some function taking a unsigned int
No need to typecast anything here because you're not changing the type. Note in your code the "value" doesn't change:
// prints the address
fprintf(stdout, "=== addr: %08x ===\n", addr);
// prints the value at that address
fprintf(stdout, "=== casted addr: %08x ===\n", *(unsigned int *)addr);
You are not changing the value. In
fprintf(stdout, "=== addr: %08x ===\n", addr); fflush(stdout);
You are accessing the address of the pointer.
In
fprintf(stdout, "=== casted addr: %08x ===\n", *(unsigned int *)address);
you are accessing the value pointed to.