Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to loop through multiple structs, like through an array?

Tags:

c

struct

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?

like image 391
ieattacos9 Avatar asked Apr 16 '26 04:04

ieattacos9


1 Answers

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.

like image 67
Jonathan Leffler Avatar answered Apr 17 '26 18:04

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!