hans
hans

Reputation: 5

How can I create an array with struct elements in C?

I want to create an array that contains elements of a structure, each element of the struct is a boolean and when accessing each array element I want to modify the value of the structure. Structure is a global variable, when modifying the array element, I want to also modify the global structure.

typedef struct
{
    bool bool1;
    bool bool2;
    bool bool2;
} struct_bool;

struct_bool my_struct;

bool array_dummy[3] = {my_struct.bool1, my_struct.bool2, my_struct.bool3};

array_dummy[0] = true;
array_dummy[1] = true;
array_dummy[2] = false;

Upvotes: 0

Views: 132

Answers (2)

Marty Cagas
Marty Cagas

Reputation: 360

My recommended approach is using anonymous structures and unions:

typedef struct {
    union {
        struct {
            bool bool1;
            bool bool2;
            bool bool3;
        };
        bool booleans[3];
    };
} struct_bool;

struct_bool my_struct;

That way you can address the elements both as a structure and as an array.

my_struct.bool1 = true;

my_struct.booleans[1] = true;
my_struct.booleans[2] = false;

This is thanks to union elements sharing their memory location. Both the anonymous structure and the array of booleans are located on the same address and thus modifying one and reading another will read that modification.

Upvotes: -1

Blindy
Blindy

Reputation: 67380

Use pointers:

bool *array_dummy[3] = { &my_struct.bool1, &my_struct.bool2, &my_struct.bool3 };

*array_dummy[0] = true;
*array_dummy[1] = true;
*array_dummy[2] = false;

Upvotes: 5

Related Questions