简体   繁体   English

如何定义指向结构的指针?

[英]How can I define pointer to the struct?

I would like to define to the struct 我想定义结构

typedef struct
{
    unsigned long GPFSEL[6];
    unsigned long Reserved_1;
    unsigned long GPSET[2];
    unsigned long Reserved_2;

//Ignoring the reserved and test bytes
} GPIO_REGS_;

One solution would be this 一个解决方案就是这样

volatile  GPIO_REGS_ * const GPIO_REGS  = ((volatile GPIO_REGS_ *) 0x20200000UL);

In this case I can reach the register as follow: 在这种情况下,我可以按如下方式登记:

GPIO_REGS->GPSET[0];

But how should I define the GPIO_REGS variable that I can use as follow 但是我应该如何定义我可以使用的GPIO_REGS变量如下

GPIO_REGS.GPSET[0];

Why the following won't work? 为什么以下不起作用?

#define GPIO_REGS  (*(( GPIO_REGS_ *) 0x20200000UL));
GPIO_REGS_ my_gpio_reg;

GPIO_REGS_ * my_gpio_reg_ptr;

my_gpio_reg_ptr = &my_gpio_reg;

The problem with the code in your question 你问题中代码的问题

#define GPIO_REGS  (*(( GPIO_REGS_ *) 0x20200000UL));

is the semicolon at the end. 最后是分号。 You should remove it 你应该删除它

#define GPIO_REGS  (*(( GPIO_REGS_ *) 0x20200000UL))

(The real lesson here is to avoid macros at all costs. They are notoriously tricky. Every time you think you understand them, you just get a false sense of security and then more buggy code is written!) (这里真正的教训是不惜一切代价避免使用宏。它们非常棘手。每当你认为你理解它们时,你就会得到一种错误的安全感,然后会写出更多错误的代码!)

Anyway, with your original use of the macro: 无论如何,与你原来使用的宏:

GPIO_REGS.GPSET[0];

it was expanded as: 它被扩展为:

(*(( GPIO_REGS_ *) 0x20200000UL));.GPSET[0];

See that the semicolon doesn't fit here? 看到分号不适合这里?

Keep your macros small. 保持你的宏小。 Don't put ; 不要放; on the end. 最后。 And always put brackets around them. 并且总是在它们周围加上括号。 The brackets should be the outermost thing - do not put a semicolon on the end. 括号应该是最外层的 - 不要在末尾加上分号。 (We could write other warnings about macros all day long. (我们可以整天写关于宏的其他警告。

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

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