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?

3
  • 1
    If you mean "int data = 4;", the answer is NO. Not in C. stackoverflow.com/questions/13716913/… Commented Oct 6, 2013 at 20:10
  • Ok so if it isn't possible how would I check if next is empty? Just a simple NULL check or what? Commented Oct 6, 2013 at 20:13
  • All zeros and all nulls would work. node foo[100] = { 0 } ; Commented Oct 6, 2013 at 20:49

1 Answer 1

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} };
Sign up to request clarification or add additional context in comments.

7 Comments

But what if I have 100,000 entries in my array? Is there a more efficient way?
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 +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.
So what happens if I have an array of nodes and I check to see if the array indices are null?
@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.)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.