Reputation: 33
Is there a way to loop through structs and assign a value to their members during the process?
I'm not really sure if I composed the question correctly, so I'll try showing it in code, that is of course invalid, but hopefully serves as better example:
struct example {
int x;
/* ... */
};
struct example s1;
struct example s2;
int *structs[] = {
s1.x,
s2.x
};
int main(void) {
for (int i = 0; i < 2; i++) {
*structs[i] = i;
}
return 0;
}
Basically, I need to automate the process of assigning values to multiple structures, but I don't know how. Is this even possible in C?
Upvotes: 3
Views: 814
Reputation: 754820
If you fix a bunch of trivial syntax errors, you can come up with:
struct example
{
int x;
/* ... */
};
struct example s1;
struct example s2;
int *structs[] = { &s1.x, &s2.x };
int main(void)
{
for (int i = 0; i < 2; i++)
{
*structs[i] = i;
}
return 0;
}
Alternatively, you could use an array of pointers to structures:
struct example
{
int x;
/* ... */
};
struct example s1;
struct example s2;
struct example *examples[] = { &s1, &s2 };
enum { NUM_EXAMPLES = sizeof(examples) / sizeof(examples[0]) };
int main(void)
{
for (int i = 0; i < NUM_EXAMPLES; i++)
{
examples[i]->x = i;
// ...
}
return 0;
}
Both compile — both work.
Upvotes: 3