简体   繁体   中英

Array of struct whose member is a pointer

I have this C code for an embedded system where I am assigning the address of Var to an struct pointer member. Problem is when I execute the code I see incorrect address instead of Var address in the structVarArray[1] . However if I modify the structVarArray type to const then I get the right address but then I cannot modify the Boolean flag as it becomes const . Any idea?

UInt8 Var;
typedef struct
{
 UInt8 * ptrVar;
 Boolean flag;
}structType;

structType structVarArray[1] =
// const structType structVarArray[1] =
{
 {&Var,  FALSE}
};

void main(void)
{
 // Code using the above array
}

Not sure how you were attempting to access the structVarArray, below is a working example.

#include <stdio.h>

unsigned char Var;
struct structType
{
    unsigned char * ptrVar;
    bool flag;
};

structType structVarArray[] =
{
    {&Var, false}
};

int main(void)
{
    *structVarArray[0].ptrVar = 50;

    printf("Var = %d\n", Var);  // prints 50

    structVarArray[0].flag = true;

    return 0;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM