maitreya
maitreya

Reputation: 13

how to access a member of a structure using a pointer offset

/* Trying to copy a value from member of one structure to another using pointers and structure offset: */

enter code here

typedef struct
{
    uint8 Value;
    uint8 Status;
} sts;

typedef struct
{
   sts CC1;
   sts CC2;
   sts CC3;
   sts CC4;
} StructTypeWrite;

typedef struct
{
   uint8 CC1;
   uint8 CC2;
   uint8 CC3;
   uint8 CC4;
} StructTypeRead;   

static StructTypeWrite WriteVariable;
static StructTypeRead ReadVariable;

void main(void)
{
    StructTypeWrite *WritePtr;
    StructTypeRead *ValPtr;
    uint8 i;

    /* Just Writing Value in order to check */
    WriteVariable.CC1.Value = 5;
    WriteVariable.CC2.Value = 30;   
    WriteVariable.CC3.Value = 40;   
    WriteVariable.CC4.Value = 45;

    WritePtr = &WriteVariable;
    ValPtr = &ReadVariable;

    for(i=0; i<4; i++) 
    {
        /* Need to copy all the members value to another structure */
        *((uint8*)ValPtr + i) = *((sts*)(uint8*)WritePtr + i)->Value;
    }
}

error during compilation is : error #75: operand of "*" must be a pointer ((uint8)ValPtr + i) = ((sts)(uint8*)WritePtr + i)->Value;

Can anyone help me where am i wrong ?

Upvotes: 1

Views: 1207

Answers (2)

fileyfood500
fileyfood500

Reputation: 1321

You are correctly computing the pointer offsets. However, you are dereferencing too many times. The arrow notation -> dereferences a struct in C. So if you are using ->, you should not also be using *. I corrected your code by using only the arrow to dereference. Like so:

for(i=0; i<4; i++) 
{
    /* Need to copy all the members value to another structure */
    *((uint8*)ValPtr + i) = ((sts*)(uint8*)WritePtr + i)->Value;
}

Notice the star I removed right after the = on the assignment line.

Edit: You should not compute pointer offsets like this in a struct, because different struct elements will be padded differently. Use the offsetof macro instead.

Like so:

uint8* newCC1Address = WritePtr + offsetof(StructTypeWrite, CC1);

This will ensure that the offset is correctly computed given the potential for different byte offsets due to padding.

Upvotes: 2

NoamD
NoamD

Reputation: 51

Avoid accessing struct members using pointer offset. The compiler may add padding bytes to get a proper alignment. see Data structure alignment Why don't you use arrays instead of structs? sts WriteVariable[4]; uint8 ReadVariable[4];

Upvotes: 1

Related Questions