0

I am trying to declare an array of structs, is it possible to initialize all array entries to a default struct value?

For example if my struct is something like

           typedef struct node
           {    int data;
                struct node* next;
           }node;

Is there a way to declare data to 4 and next to null? What about 0 and null?

Nicolas Henneaux
  • 11,507
  • 11
  • 57
  • 82
Paul the Pirate
  • 767
  • 3
  • 7
  • 10

1 Answers1

3

Sure:

node x[4] = { {0, NULL}, {1, NULL}, {2, NULL}, {3, NULL} };

Even this should be fine:

node y[4] = { {0, y + 1}, {1, y + 2}, {2, y + 3}, {3, NULL} };
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • 1
    But what if I have 100,000 entries in my array? Is there a more efficient way? – Paul the Pirate Oct 06 '13 at 20:10
  • For 100,000 entries you'd probably initialising from persistent storage so efficiency would not be a concern as the performance would be io-bound. Kerrek SB's answer stands as 'most likely the best solution' in my opinion so gets +1. – Bathsheba Oct 06 '13 at 20:13
  • @Bathsheba +1 I concur. There is no way via some magic declaration to initialize a sequence that increments ad-nausem to some declared upper-bound. Even a regular fixed trivial array, `int ar[N]` has the same restriction. The structure doesn't add extra complexity to that which is fundamentally impossible to begin with. – WhozCraig Oct 06 '13 at 20:17
  • So what happens if I have an array of nodes and I check to see if the array indices are null? – Paul the Pirate Oct 06 '13 at 20:19
  • @PaulthePirate: What are "array indices"?! – Kerrek SB Oct 06 '13 at 21:48
  • 1
    @PaulthePirate: Re 100000 entries: If you really want to *initialize* them, then you must spell out the initializer. If you're happy to assign the values after initialization, you can do it in a simple loop. (In C++ you could use templates to produce compact initializers, though.) – Kerrek SB Oct 06 '13 at 21:50
  • @KerrekSB Indices is the plural of index, so I just meant each node at a specific index. – Paul the Pirate Oct 06 '13 at 22:26