How do we use structs?

后端 未结 2 1390
离开以前
离开以前 2021-01-25 18:15

The main problem I\'m having is having so many parameters, which I just want to get rid of, and yes I do not understand the logic of structs. However, it is becoming a bit more

相关标签:
2条回答
  • 2021-01-25 18:50

    Refers to general using of struct, not the technical side: (because it seems to me that you do not understand the logic in it)

    You should use struct for group of variables they part of one thing.

    For example, struct point (to represent point in in space) will contain int for X and int for Y.

    You should use array for group of variables they the relation between their is serial.

    For example: students in class, since you want to do same actions on each student in sequence.

    0 讨论(0)
  • 2021-01-25 18:59
    typedef struct _foo
    {
        int x1, x2, x3,..., x20;
    } foo;
    
    int add(const foo *pBar)
    {
        return pBar->x1 + pBar->x2 + pBar->x3 + ... + pBar->x20;
    }
    
    int main()
    {
        // declare and initialize the struct
        foo bar = { 1, 2, 3, ..., 20 };
    
        // an alternative way of initializing the struct:
        bar.x1 = 1;
        bar.x2 = 2;
        bar.x3 = 3;
         :
        bar.x20 = 20;
    
        int total = add(&bar);
    }
    
    0 讨论(0)
提交回复
热议问题