kingkong kingkong - 3 months ago 6
C Question

Save content of member of struct to variable

Sorry, but I'm relative newby to C.
I have a struct which contains registers. At a specific point in the program I would like to save the content of some specific registers to a variable. It looks like:

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


As values I get the addresses, like 0xFFFFFFFF, 0xFFFFFFFF. What am I doing wrong?

Answer

I assume, for sake of discussion, that uint32 is an unsigned integral type.

Defining a pointer does not create instance of the struct. So you need to create an instance for the pointer to point at, and explicitly initialise the pointer so it does.

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;

}

Failure to initialise the pointer (i.e. not making it point at a valid iobject) means all attempts to use the members via the pointer will yield undefined behaviour.

Comments