c - 将结构体成员的内容保存到变量

标签 c

抱歉,但我对 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/

相关文章:

c - SDL2 音频回调限制为 8 位?

c++ - 比较从 C 中的套接字接收的字符串数据

c - WinSDK 7.1 : Getting Started with the Windows SDK Tools for Native Windows app development?

在函数c中更改数组

c - C 中的 Anagram : How do I know if every element of the int array is set to zero?

c - 如何定义字符串数组的结尾

c - 当我按下一个键时,如何使这个球体围绕另一个球体旋转?

c - 为什么 gcc 返回 0 而不是堆栈分配变量的地址?

c - 当 fd 是一个普通文件时,linux 系统调用 read(fd, buf, count) 是否返回小于 count?

c - 在没有任何外部库或头文件(如 math.h)的情况下查找数字的 n 次方根的程序