I need to help how to handle this situation. Variable DestinationAddress
which contains start value of memory. And I want to use pointer to write to the address the data. Is it OK?
Example:
long Data32;
long DestinationAddress;
long *temp;
Data32 = 0x00112233;
DestinationAddress = 0x00280000;
temp = DestinationAddress;
*temp = Data32;
When your variables are declared as:
long Data32;
long DestinationAddress;
long *temp;
You may not use
temp = DestinationAddress;
You may use:
temp = &DestinationAddress;
Then, using:
*temp = Data32;
is a valid way to set the value of DestinationAddress
to Data32
.
However, the name DestinationAddress
and the type used to declare it, long
, don't seem to match. If you want DestinationAddress
to store an address of a long
, it needs to be declared as:
long* DestinationAddress;
If you want to use an integral type instead of a long*
to store an address, the types to use are intptr_t
or uintptr_t
.
uintptr_t Data32;
uintptr_t DestinationAddress;
uintptr_t* temp;
Data32 = 0x00112233;
DestinationAddress = 0x00280000;
temp = &DestinationAddress;
*temp = Data32;
Update, in response to OP's comment
You need to use:
long Data32;
uintptr_t DestinationAddress;
long* temp;
Data32 = 0x00112233;
DestinationAddress = 0x00280000;
temp = (long*)DestinationAddress;
*temp = Data32;
In embedded systems, many hardware registers are located at specific addresses. The software needs to write to and read from these addresses.
The classic (C style) idiom is:
#define USB_STATUS_REGISTER ((uint16_t *) (0x40008250))
uint16_t const * const p_status_register = USB_STATUS_REGISTER;
uint16_t status = *p_status_register;
It's fine as long as 0x00280000
is a valid address - but you should really consider using uintptr_t
for storing pointer values if available (instead of long
in your example).
But DestinationAddress
is an integer. So, you'd need to convert it with a case (otherwise, a compiler might warn about it):
temp = (long*)DestinationAddress;
*temp = Data32;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.