Initialization array of structs - {NULL} vs {}












1















If I have this struct:



typedef struct MyStruct
{
int type1;
char *type2;
char type3[CHARS_AMOUNT];
} MyStruct;


What would be the difference between following initialization:



option 1:



int main(int argc, char *argv)
{
MyStruct someObjects[5] = {};
}


option 2:



int main(int argc, char *argv)
{
MyStruct someObjects[5] = {NULL};
}









share|improve this question



























    1















    If I have this struct:



    typedef struct MyStruct
    {
    int type1;
    char *type2;
    char type3[CHARS_AMOUNT];
    } MyStruct;


    What would be the difference between following initialization:



    option 1:



    int main(int argc, char *argv)
    {
    MyStruct someObjects[5] = {};
    }


    option 2:



    int main(int argc, char *argv)
    {
    MyStruct someObjects[5] = {NULL};
    }









    share|improve this question

























      1












      1








      1








      If I have this struct:



      typedef struct MyStruct
      {
      int type1;
      char *type2;
      char type3[CHARS_AMOUNT];
      } MyStruct;


      What would be the difference between following initialization:



      option 1:



      int main(int argc, char *argv)
      {
      MyStruct someObjects[5] = {};
      }


      option 2:



      int main(int argc, char *argv)
      {
      MyStruct someObjects[5] = {NULL};
      }









      share|improve this question














      If I have this struct:



      typedef struct MyStruct
      {
      int type1;
      char *type2;
      char type3[CHARS_AMOUNT];
      } MyStruct;


      What would be the difference between following initialization:



      option 1:



      int main(int argc, char *argv)
      {
      MyStruct someObjects[5] = {};
      }


      option 2:



      int main(int argc, char *argv)
      {
      MyStruct someObjects[5] = {NULL};
      }






      c arrays struct






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 14 '18 at 23:12









      Super MarioSuper Mario

      1979




      1979
























          3 Answers
          3






          active

          oldest

          votes


















          2














          The difference is that the first is illegal in standard C, and the second may or may not be.



          {} in an initializer is not legal in C; you need at least one element between the { and }. (Some compilers might permit it as an extension; I think gcc does.)



          A common idiom is



          some_type blah = { 0 };


          The initial element is initialized to 0 (which could be a null pointer, floating-point zero, a null character, etc.), and the remaining unspecified elements are initialized to zero for the appropriate type.



          With the {NULL} initializer you're trying to initialize someObjects[0].type1, an int to NULL. The NULL macro is intended to be used as a null pointer constant. It may or may not be defined as a constant 0, so the legality of your initializer is implementation-specific.



          Just write



          MyStruct someObjects[5] = {0};





          share|improve this answer
























          • Is it the same in gcc to write { 0 } and { } ?

            – Super Mario
            Nov 15 '18 at 12:32






          • 1





            @SuperMario: Not in all cases. Another gcc extension is that it permits empty structures. So struct empty { } obj = { }; is valid in GNU C, but struct empty { } obj = { 0 }; gets at least a warning. Apart from that, as far as I know, they should be equivalent.

            – Keith Thompson
            Nov 15 '18 at 22:03



















          2














          MyStruct someObjects[5] = {}; isn't conformant C and
          whether MyStruct someObjects[5] = {NULL}; is conformant C is implementation defined*.



          You should initialize it with MyStruct someObjects[5] = {0};. {0} is the way to default/zero-initialize any array, aggregate object or compound literal in C.



          {0} works for default/zero-initialization because 6.7.9p19 and 6.7.9p20 will cause the 0 to recursively target the first primitive object, because every primitive data object in C is either numerical or a pointer and therefore initialiazable with 0 and finally because 6.7.9p21 says that:




          If there are fewer initializers in a brace-enclosed list than there
          are elements or members of an aggregate, or fewer characters in a
          string literal used to initialize an array of known size than there
          are elements in the array, the remainder of the aggregate shall be
          initialized implicitly the same as objects that have static storage
          duration.






          *NULL could be defined as 0 in which case {NULL} is OK, or it could just as well be defined (void*)0 in which case {NULL}'s not OK in your case because recursively, you're array's first primitive object (int type1;) is not a pointer initalizable from (void*) or even a pointer.






          share|improve this answer

































            2














            The first version is immediately illegal. C language does not support {} initializers.



            The second version is generally illegal, even though it might "compile" in some implementations. In this case, in accordance with the rules of aggregate initialization your NULL will act as an initializer for someObjects[0].type1 field. This field has type int. However, even though in many implementations you might be able to successfully initialize int objects with NULL, in general case it is not possible. NULL is intended to be used in pointer context, not in integer context.



            If you want to zero-initialize your entire array, the proper way to do it is



            MyStruct someObjects[5] = { 0 };





            share|improve this answer


























            • I work with gcc, it compiled without any problem

              – Super Mario
              Nov 15 '18 at 8:58











            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53310148%2finitialization-array-of-structs-null-vs%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            The difference is that the first is illegal in standard C, and the second may or may not be.



            {} in an initializer is not legal in C; you need at least one element between the { and }. (Some compilers might permit it as an extension; I think gcc does.)



            A common idiom is



            some_type blah = { 0 };


            The initial element is initialized to 0 (which could be a null pointer, floating-point zero, a null character, etc.), and the remaining unspecified elements are initialized to zero for the appropriate type.



            With the {NULL} initializer you're trying to initialize someObjects[0].type1, an int to NULL. The NULL macro is intended to be used as a null pointer constant. It may or may not be defined as a constant 0, so the legality of your initializer is implementation-specific.



            Just write



            MyStruct someObjects[5] = {0};





            share|improve this answer
























            • Is it the same in gcc to write { 0 } and { } ?

              – Super Mario
              Nov 15 '18 at 12:32






            • 1





              @SuperMario: Not in all cases. Another gcc extension is that it permits empty structures. So struct empty { } obj = { }; is valid in GNU C, but struct empty { } obj = { 0 }; gets at least a warning. Apart from that, as far as I know, they should be equivalent.

              – Keith Thompson
              Nov 15 '18 at 22:03
















            2














            The difference is that the first is illegal in standard C, and the second may or may not be.



            {} in an initializer is not legal in C; you need at least one element between the { and }. (Some compilers might permit it as an extension; I think gcc does.)



            A common idiom is



            some_type blah = { 0 };


            The initial element is initialized to 0 (which could be a null pointer, floating-point zero, a null character, etc.), and the remaining unspecified elements are initialized to zero for the appropriate type.



            With the {NULL} initializer you're trying to initialize someObjects[0].type1, an int to NULL. The NULL macro is intended to be used as a null pointer constant. It may or may not be defined as a constant 0, so the legality of your initializer is implementation-specific.



            Just write



            MyStruct someObjects[5] = {0};





            share|improve this answer
























            • Is it the same in gcc to write { 0 } and { } ?

              – Super Mario
              Nov 15 '18 at 12:32






            • 1





              @SuperMario: Not in all cases. Another gcc extension is that it permits empty structures. So struct empty { } obj = { }; is valid in GNU C, but struct empty { } obj = { 0 }; gets at least a warning. Apart from that, as far as I know, they should be equivalent.

              – Keith Thompson
              Nov 15 '18 at 22:03














            2












            2








            2







            The difference is that the first is illegal in standard C, and the second may or may not be.



            {} in an initializer is not legal in C; you need at least one element between the { and }. (Some compilers might permit it as an extension; I think gcc does.)



            A common idiom is



            some_type blah = { 0 };


            The initial element is initialized to 0 (which could be a null pointer, floating-point zero, a null character, etc.), and the remaining unspecified elements are initialized to zero for the appropriate type.



            With the {NULL} initializer you're trying to initialize someObjects[0].type1, an int to NULL. The NULL macro is intended to be used as a null pointer constant. It may or may not be defined as a constant 0, so the legality of your initializer is implementation-specific.



            Just write



            MyStruct someObjects[5] = {0};





            share|improve this answer













            The difference is that the first is illegal in standard C, and the second may or may not be.



            {} in an initializer is not legal in C; you need at least one element between the { and }. (Some compilers might permit it as an extension; I think gcc does.)



            A common idiom is



            some_type blah = { 0 };


            The initial element is initialized to 0 (which could be a null pointer, floating-point zero, a null character, etc.), and the remaining unspecified elements are initialized to zero for the appropriate type.



            With the {NULL} initializer you're trying to initialize someObjects[0].type1, an int to NULL. The NULL macro is intended to be used as a null pointer constant. It may or may not be defined as a constant 0, so the legality of your initializer is implementation-specific.



            Just write



            MyStruct someObjects[5] = {0};






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 14 '18 at 23:19









            Keith ThompsonKeith Thompson

            192k26289484




            192k26289484













            • Is it the same in gcc to write { 0 } and { } ?

              – Super Mario
              Nov 15 '18 at 12:32






            • 1





              @SuperMario: Not in all cases. Another gcc extension is that it permits empty structures. So struct empty { } obj = { }; is valid in GNU C, but struct empty { } obj = { 0 }; gets at least a warning. Apart from that, as far as I know, they should be equivalent.

              – Keith Thompson
              Nov 15 '18 at 22:03



















            • Is it the same in gcc to write { 0 } and { } ?

              – Super Mario
              Nov 15 '18 at 12:32






            • 1





              @SuperMario: Not in all cases. Another gcc extension is that it permits empty structures. So struct empty { } obj = { }; is valid in GNU C, but struct empty { } obj = { 0 }; gets at least a warning. Apart from that, as far as I know, they should be equivalent.

              – Keith Thompson
              Nov 15 '18 at 22:03

















            Is it the same in gcc to write { 0 } and { } ?

            – Super Mario
            Nov 15 '18 at 12:32





            Is it the same in gcc to write { 0 } and { } ?

            – Super Mario
            Nov 15 '18 at 12:32




            1




            1





            @SuperMario: Not in all cases. Another gcc extension is that it permits empty structures. So struct empty { } obj = { }; is valid in GNU C, but struct empty { } obj = { 0 }; gets at least a warning. Apart from that, as far as I know, they should be equivalent.

            – Keith Thompson
            Nov 15 '18 at 22:03





            @SuperMario: Not in all cases. Another gcc extension is that it permits empty structures. So struct empty { } obj = { }; is valid in GNU C, but struct empty { } obj = { 0 }; gets at least a warning. Apart from that, as far as I know, they should be equivalent.

            – Keith Thompson
            Nov 15 '18 at 22:03













            2














            MyStruct someObjects[5] = {}; isn't conformant C and
            whether MyStruct someObjects[5] = {NULL}; is conformant C is implementation defined*.



            You should initialize it with MyStruct someObjects[5] = {0};. {0} is the way to default/zero-initialize any array, aggregate object or compound literal in C.



            {0} works for default/zero-initialization because 6.7.9p19 and 6.7.9p20 will cause the 0 to recursively target the first primitive object, because every primitive data object in C is either numerical or a pointer and therefore initialiazable with 0 and finally because 6.7.9p21 says that:




            If there are fewer initializers in a brace-enclosed list than there
            are elements or members of an aggregate, or fewer characters in a
            string literal used to initialize an array of known size than there
            are elements in the array, the remainder of the aggregate shall be
            initialized implicitly the same as objects that have static storage
            duration.






            *NULL could be defined as 0 in which case {NULL} is OK, or it could just as well be defined (void*)0 in which case {NULL}'s not OK in your case because recursively, you're array's first primitive object (int type1;) is not a pointer initalizable from (void*) or even a pointer.






            share|improve this answer






























              2














              MyStruct someObjects[5] = {}; isn't conformant C and
              whether MyStruct someObjects[5] = {NULL}; is conformant C is implementation defined*.



              You should initialize it with MyStruct someObjects[5] = {0};. {0} is the way to default/zero-initialize any array, aggregate object or compound literal in C.



              {0} works for default/zero-initialization because 6.7.9p19 and 6.7.9p20 will cause the 0 to recursively target the first primitive object, because every primitive data object in C is either numerical or a pointer and therefore initialiazable with 0 and finally because 6.7.9p21 says that:




              If there are fewer initializers in a brace-enclosed list than there
              are elements or members of an aggregate, or fewer characters in a
              string literal used to initialize an array of known size than there
              are elements in the array, the remainder of the aggregate shall be
              initialized implicitly the same as objects that have static storage
              duration.






              *NULL could be defined as 0 in which case {NULL} is OK, or it could just as well be defined (void*)0 in which case {NULL}'s not OK in your case because recursively, you're array's first primitive object (int type1;) is not a pointer initalizable from (void*) or even a pointer.






              share|improve this answer




























                2












                2








                2







                MyStruct someObjects[5] = {}; isn't conformant C and
                whether MyStruct someObjects[5] = {NULL}; is conformant C is implementation defined*.



                You should initialize it with MyStruct someObjects[5] = {0};. {0} is the way to default/zero-initialize any array, aggregate object or compound literal in C.



                {0} works for default/zero-initialization because 6.7.9p19 and 6.7.9p20 will cause the 0 to recursively target the first primitive object, because every primitive data object in C is either numerical or a pointer and therefore initialiazable with 0 and finally because 6.7.9p21 says that:




                If there are fewer initializers in a brace-enclosed list than there
                are elements or members of an aggregate, or fewer characters in a
                string literal used to initialize an array of known size than there
                are elements in the array, the remainder of the aggregate shall be
                initialized implicitly the same as objects that have static storage
                duration.






                *NULL could be defined as 0 in which case {NULL} is OK, or it could just as well be defined (void*)0 in which case {NULL}'s not OK in your case because recursively, you're array's first primitive object (int type1;) is not a pointer initalizable from (void*) or even a pointer.






                share|improve this answer















                MyStruct someObjects[5] = {}; isn't conformant C and
                whether MyStruct someObjects[5] = {NULL}; is conformant C is implementation defined*.



                You should initialize it with MyStruct someObjects[5] = {0};. {0} is the way to default/zero-initialize any array, aggregate object or compound literal in C.



                {0} works for default/zero-initialization because 6.7.9p19 and 6.7.9p20 will cause the 0 to recursively target the first primitive object, because every primitive data object in C is either numerical or a pointer and therefore initialiazable with 0 and finally because 6.7.9p21 says that:




                If there are fewer initializers in a brace-enclosed list than there
                are elements or members of an aggregate, or fewer characters in a
                string literal used to initialize an array of known size than there
                are elements in the array, the remainder of the aggregate shall be
                initialized implicitly the same as objects that have static storage
                duration.






                *NULL could be defined as 0 in which case {NULL} is OK, or it could just as well be defined (void*)0 in which case {NULL}'s not OK in your case because recursively, you're array's first primitive object (int type1;) is not a pointer initalizable from (void*) or even a pointer.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 14 '18 at 23:31

























                answered Nov 14 '18 at 23:17









                PSkocikPSkocik

                33.8k65475




                33.8k65475























                    2














                    The first version is immediately illegal. C language does not support {} initializers.



                    The second version is generally illegal, even though it might "compile" in some implementations. In this case, in accordance with the rules of aggregate initialization your NULL will act as an initializer for someObjects[0].type1 field. This field has type int. However, even though in many implementations you might be able to successfully initialize int objects with NULL, in general case it is not possible. NULL is intended to be used in pointer context, not in integer context.



                    If you want to zero-initialize your entire array, the proper way to do it is



                    MyStruct someObjects[5] = { 0 };





                    share|improve this answer


























                    • I work with gcc, it compiled without any problem

                      – Super Mario
                      Nov 15 '18 at 8:58
















                    2














                    The first version is immediately illegal. C language does not support {} initializers.



                    The second version is generally illegal, even though it might "compile" in some implementations. In this case, in accordance with the rules of aggregate initialization your NULL will act as an initializer for someObjects[0].type1 field. This field has type int. However, even though in many implementations you might be able to successfully initialize int objects with NULL, in general case it is not possible. NULL is intended to be used in pointer context, not in integer context.



                    If you want to zero-initialize your entire array, the proper way to do it is



                    MyStruct someObjects[5] = { 0 };





                    share|improve this answer


























                    • I work with gcc, it compiled without any problem

                      – Super Mario
                      Nov 15 '18 at 8:58














                    2












                    2








                    2







                    The first version is immediately illegal. C language does not support {} initializers.



                    The second version is generally illegal, even though it might "compile" in some implementations. In this case, in accordance with the rules of aggregate initialization your NULL will act as an initializer for someObjects[0].type1 field. This field has type int. However, even though in many implementations you might be able to successfully initialize int objects with NULL, in general case it is not possible. NULL is intended to be used in pointer context, not in integer context.



                    If you want to zero-initialize your entire array, the proper way to do it is



                    MyStruct someObjects[5] = { 0 };





                    share|improve this answer















                    The first version is immediately illegal. C language does not support {} initializers.



                    The second version is generally illegal, even though it might "compile" in some implementations. In this case, in accordance with the rules of aggregate initialization your NULL will act as an initializer for someObjects[0].type1 field. This field has type int. However, even though in many implementations you might be able to successfully initialize int objects with NULL, in general case it is not possible. NULL is intended to be used in pointer context, not in integer context.



                    If you want to zero-initialize your entire array, the proper way to do it is



                    MyStruct someObjects[5] = { 0 };






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 14 '18 at 23:43

























                    answered Nov 14 '18 at 23:16









                    AnTAnT

                    259k32417659




                    259k32417659













                    • I work with gcc, it compiled without any problem

                      – Super Mario
                      Nov 15 '18 at 8:58



















                    • I work with gcc, it compiled without any problem

                      – Super Mario
                      Nov 15 '18 at 8:58

















                    I work with gcc, it compiled without any problem

                    – Super Mario
                    Nov 15 '18 at 8:58





                    I work with gcc, it compiled without any problem

                    – Super Mario
                    Nov 15 '18 at 8:58


















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53310148%2finitialization-array-of-structs-null-vs%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Bressuire

                    Vorschmack

                    Quarantine