I am having trouble accessing data in a nested Struct. I am trying to realize a SPI-Communication between two MCUs. The Idea was to provide an easy to manipulate Struct to other functions which is nested in the handler and serialized before transmission. Accessing the struct during serialization does not work however.
I tried to create a simplified model of my datastructure below.
typedef struct a_t{
uint16_t member1;
uint8_t member2;
} a_t;
typedef struct b_t
{
volatile a_t* aPtr;
volatile uint8_t arrayC[3];
} b_t;
a_t a;
a.member1 = 0xABCD;
a.member2 = 0xEF;
b_t b;
b_t* bPtr = &b;
bPtr->aPtr = &a;
To my Understanding, the struct b now contains a Pointer to struct a while bPtr points to struct b. So if i dereference
bPtr->aPtr
i should get a Pointer to Struct a. If i dereference further, I should be able to access the members of a like this
bPtr->arrayC[0] = (((bPtr->aPtr->member1) >> 8) & 0xFF);
bPtr->arrayC[1] = ((bPtr->aPtr->member1) & 0xFF);
bPtr>arrayC[2] = bPtr->aPtr->member2;
Which should lead to arrayC containing the following data:
bPtr->arrayC[0] == 0xAB;
bPtr->arrayC[1] == 0xCD;
bPtr->arrayC[2] == 0xEF;
Sadly i cannot find this is the case with my code. In my Case the Values of arrayC are as followed if i try to assign them like shown above
bPtr->arrayC[0] == 0x00;
bPtr->arrayC[1] == 0x00;
bPtr->arrayC[2] == 0x00;
If I assign Values as followed
bPtr->arrayC[0] = 0xAB;
The Value changes as intended, so the error must be in the expression
(((bPtr->aPtr->member1) >> 8) & 0xFF);
((bPtr->aPtr->member1) & 0xFF);
bPtr->aPtr->member2;
I am Sorry if this is a silly question, I could find some double pointer references in other posts. But I did not find an explanation why my solution does not work elsewhere so i am grateful if a more experienced programmer is able to explain my mistake to me.
Edit: I corrected a mistake in the Model in which i wrongly addresed member bPtr->aPtr as b->a
Edit2: The dereference does work when tested with the following compiler
godbolt.org/z/Wdcahndxh
However the same code produces 0x00 within my MCU (MCU: MKE02Z Processor: Cortex M0 Compiler: ARM6 C99)
CodePudding user response:
I am so Sorry. I found my mistake. I switched the order of the arguments for my initialization function and mistakenly put the pointer to the rxBuffer into the txbufferptr of the SPI-handler. The rxBuffer was empty, therefore yielding only 0.
I am Thankful for everyone who took the time to help me. I am relatively new, should I delete this question? Stackoverflow warns me that i could be blocked from asking if I do this.
CodePudding user response:
Sir,
To my Understanding, the struct b now contains a Pointer to struct a while bPtr points to struct b. So if i dereference
Sorry, that is wrong, you must refactor from there, you need to use a structure member to store the address, not the struct name:
// b_t struct has a member named aPtr, by sure you must
// store the address of a here
b.aPtr = &a;