简体   繁体   English

如何使用指针处理存储在变量中的地址?

[英]How to handle address stored in variable with pointer?

I need to help how to handle this situation. 我需要帮助如何处理这种情况。 Variable DestinationAddress which contains start value of memory. 变量DestinationAddress包含内存的起始值。 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 . 是将DestinationAddress的值设置为Data32的有效方法。

However, the name DestinationAddress and the type used to declare it, long , don't seem to match. 但是,名称DestinationAddress和用于声明它的类型long似乎不匹配。 If you want DestinationAddress to store an address of a long , it needs to be declared as: 如果要DestinationAddress存储long的地址,则需要将其声明为:

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 . 如果要使用整数类型而不是long*来存储地址, intptr_t使用的类型是intptr_tuintptr_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 更新,以回应OP的评论

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: 经典(C风格)的成语是:

#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). 只要0x00280000是有效地址就可以了-但您应该考虑使用uintptr_t (如果可用)来存储指针值(而不是示例中的long )。

But DestinationAddress is an integer. 但是DestinationAddress是整数。 So, you'd need to convert it with a case (otherwise, a compiler might warn about it): 因此,您需要使用大小写对其进行转换(否则,编译器可能会发出警告):

temp = (long*)DestinationAddress;
*temp = Data32;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM