4

I have a 3dimensional array, how do I initialize it to a default value without having 3 loops.

dummy[4][4][1024]

, how do I initialize all the elements to 12?

3
  • 7
    What's wrong with 3 loops? It is the clearest way to initialize the array. Have pity on the reader. Commented May 25, 2012 at 21:21
  • I agree, I was wondering if I can do all in oneshot, some compilers and in some other platforms we can directly initialize, was checking how does that work in C Commented May 25, 2012 at 21:30
  • possible duplicate of Fastest way to zero out a 2d array in C? Commented May 29, 2012 at 8:34

3 Answers 3

10

Since the 3-d array is a contiguous block of memory, you can view it as a 1-d array

int i, *dummy2 = &dummy[0][0][0];
for(i = 0; i < 4*4*1024; ++i)
    dummy2[i] = 12;
Sign up to request clarification or add additional context in comments.

10 Comments

That's undefined behaviour.
@DanielFischer you need to declare int i too :)
BTW what's wrong with int *dummy2 = (int *)dummy instead of &dummy[0][0][0]?
Nothing. I just thought of taking the address first, @EitanT.
@EitanT: explicit casts may hide bugs. This version will fail to compile when the base type of the array changes to, say, long long. The version with the explicit cast still compiles but produces the wrong behavior.
|
7

Come on guys - let's do it the simple way that always works:


for(int i = 0; i < 4; i++)
{
  for(int j = 0; j < 4; j++)
  {
    for(int k = 0; k < 1024; k++)
    {
      dummy[i][j][k] = 12;
    }
  }
}

3 Comments

I also like this one better. Especially since compilers may well optimize this code and make it as good as the most voted answer.
@betabandido Even if not, the difference would be marginal. The only reason for treating it as a 1-d array was that the OP asked to do it "without having 3 loops".
@DanielFischer that's a good one... my eyes skipped that part :)
5

The default initialization to all zeros is just that:

unsigned dummy[4][4][1024] = { 0 };

If you want to initialize particular elements (and all others to zero) do this

unsigned dummy[4][4][1024] = { { { 5 }, { 0, 4 } } };

and if your compiler knows C99 use designated initializers

unsigned dummy[4][4][1024] = { [3] = { [2] = { [0] = 7 }, [1] = { [2] = 3, [1] = 4 } } };

and if you really insist to use all 12, just repeat the 12 16384 times :)

Comments

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.