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

前端 未结 15 2690
予麋鹿
予麋鹿 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-22 00:05

    If MS has not updated to C99, MY_TYPE a = { true,15,0.123 };

    0 讨论(0)
  • 2020-11-22 00:05

    This can be done in different ways:

    MY_TYPE a = { true, 1, 0.1 };
    
    MY_TYPE a = { .stuff = 0.1, .flag = true, .value = 1 }; //designated initializer, not available in c++
    
    MY_TYPE a;
    a = (MY_TYPE) { true,  1, 0.1 };
    
    MY_TYPE m (true, 1, 0.1); //works in C++, not available in C
    

    Also, you can define member while declaring structure.

    #include <stdio.h>
    
    struct MY_TYPE
    {
        int a;
        int b;
    }m = {5,6};
    
    int main()
    {
        printf("%d  %d\n",m.a,m.b);    
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-22 00:06

    You've almost got it...

    MY_TYPE a = { true,15,0.123 };
    

    Quick search on 'struct initialize c' shows me this

    0 讨论(0)
提交回复
热议问题