How to use a struct inside another struct?

前端 未结 7 1329
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-05 21:05

I want to use a nested structure but i dont know how to enter data in it, for example:

struct A {
    int data;
    struct B;
};
struct B {
    int number;
};


        
相关标签:
7条回答
  • 2021-02-05 21:39

    I have the somewhat like the following code running for a while live now and it works.

    //define a timer
    struct lightTimer {
      unsigned long time;                                                 //time in seconds since midnight so range is 0-86400
      byte          percentage;                                           // in percentage so range is 0-100
    };
    
    //define a list of timers
    struct lightTable {
      lightTimer timer[50];
      int        otherVar;
    };
    
    //and make 5 instances
    struct lightTable channel[5];                           //all channels are now memory allocated
    

    @zx485: EDIT: Edited/cleaned the code. Excuse for the raw dump.

    Explanation:

    Define a lightTimer. Basically a struct that contains 2 vars.

    struct lightTimer {
    

    Define a lightTable. First element is a lightTimer.

    struct lightTable {
    

    Make an actual (named) instance:

    struct lightTable channel[5];
    

    We now have 5 channels with 50 timers.

    Access like:

    channel[5].timer[10].time = 86400;
    channel[5].timer[10].percentage = 50;
    channel[2].otherVar = 50000;
    
    0 讨论(0)
提交回复
热议问题