抱歉,但我对 C 来说还是个新手。 我有一个包含寄存器的结构。在程序中的特定点,我想将某些特定寄存器的内容保存到变量中。它看起来像:
typedef struct Register // Struct with the registers
{
uint32 REG1;
uint32 REG2;
uint32 REG3;
uint32 REG4;
} Register_t;
Register_t *pToRegister_t; // Pointer to the struct
uint32 contentREG1;
uint32 contentREG2;
contentREG1 = (*pToRegister_t).REG1 // in contentREG1 I need to store the value of REG1
contentREG2 = (*pToRegister_t).REG2 // in contentREG1 I need to store the value of REG1
作为值,我得到地址,例如 0xFFFFFFFF、0xFFFFFFFF。我做错了什么?
最佳答案
为了便于讨论,我假设 uint32
是无符号整数类型。
定义指针不会创建struct
的实例。因此,您需要为指针创建一个指向的实例,并显式初始化该指针。
typedef struct Register // Struct with the registers
{
uint32 REG1;
uint32 REG2;
uint32 REG3;
uint32 REG4;
} Register_t;
int main()
{
Register_t *pToRegister_t; // Pointer to the struct
Register_t thing = {1U, 2U, 3U, 4U};
uint32 contentREG1;
uint32 contentREG2;
uint32 contentREG3;
pToRegister_t = &thing; // make the pointer point at a valid instance
contentREG1 = (*pToRegister_t).REG1; // access thing.REG1
contentREG2 = pToRegister_t->REG2; // alternative - access thing.REG2
contentREG3 = thing.REG3;
}
未能初始化指针(即未使其指向有效的 iobject)意味着通过指针使用成员的所有尝试都将产生未定义的行为。
关于c - 将结构体成员的内容保存到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39146688/