C语言 指向特定固定地址的指针

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2389251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:44:24  来源:igfitidea点击:

Pointer to a specific fixed address

cpointers

提问by Peter Luke

How do you assign a specific memory address to a pointer?

如何为指针分配特定的内存地址?

The Special Function Registers in a microcontroller such AVR m128 has fixed addresses, the AVR GCC defines the SFR in the io.h header file, but I want to handle it myself.

AVR m128 等微控制器中的特殊功能寄存器具有固定地址,AVR GCC 在 io.h 头文件中定义了 SFR,但我想自己处理。

回答by Carl Norum

Sure, no problem. You can just assign it directly to a variable:

好没问题。您可以直接将其分配给变量:

volatile unsigned int *myPointer = (volatile unsigned int *)0x12345678;

What I usually do is declare a memory-mapped I/O macro:

我通常做的是声明一个内存映射 I/O 宏:

#define mmio32(x)   (*(volatile unsigned long *)(x))

And then define my registers in a header file:

然后在头文件中定义我的寄存器:

#define SFR_BASE    (0xCF800000)
#define SFR_1       (SFR_BASE + 0x0004)
#define SFR_2       (SFR_BASE + 0x0010)

And then use them:

然后使用它们:

unsigned long registerValue = mmio32(SFR_1); // read
mmio32(SFR2) = 0x85748312;                   // write