How to initialize a struct in accordance with C programming language standards

前端 未结 15 2671
予麋鹿
予麋鹿 2020-11-21 22:59

I want to initialize a struct element, split in declaration and initialization. This is what I have:

typedef struct MY_TYPE {
  bool flag;
  short int value;         


        
15条回答
  •  一生所求
    2020-11-21 23:48

    I didn't like any of these answers so I made my own. I don't know if this is ANSI C or not, it's just GCC 4.2.1 in it's default mode. I never can remember the bracketing so I start with a subset of my data and do battle with compiler error messages until it shuts up. Readability is my first priority.

        // in a header:
        typedef unsigned char uchar;
    
        struct fields {
          uchar num;
          uchar lbl[35];
        };
    
        // in an actual c file (I have 2 in this case)
        struct fields labels[] = {
          {0,"Package"},
          {1,"Version"},
          {2,"Apport"},
          {3,"Architecture"},
          {4,"Bugs"},
          {5,"Description-md5"},
          {6,"Essential"},
          {7,"Filename"},
          {8,"Ghc-Package"},
          {9,"Gstreamer-Version"},
          {10,"Homepage"},
          {11,"Installed-Size"},
          {12,"MD5sum"},
          {13,"Maintainer"},
          {14,"Modaliases"},
          {15,"Multi-Arch"},
          {16,"Npp-Description"},
          {17,"Npp-File"},
          {18,"Npp-Name"},
          {19,"Origin"}
        };
    

    The data may start life as a tab-delimited file that you search-replace to massage into something else. Yes, this is Debian stuff. So one outside pair of {} (indicating the array), then another pair for each struct inside. With commas between. Putting things in a header isn't strictly necessary, but I've got about 50 items in my struct so I want them in a separate file, both to keep the mess out of my code and so it's easier to replace.

提交回复
热议问题