3

I was wondering if there is a shorthand way to initialise a 2D or 3D array in C similar to the following syntax:

int array[1024] = {[0 ... 1023] = 5};
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Liam Lacey
  • 215
  • 3
  • 7
  • 1
    You apparently left out the "1D" in your title, which is what your posted code actually is. Not sure what the "D" has to do with your question, come to think of it. – WhozCraig Dec 05 '14 at 11:06
  • You example is a gcc extension. What do you mean by *in C*? – 2501 Dec 05 '14 at 11:13
  • That's a [GCC extension](https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html), it's not standard C. – unwind Dec 05 '14 at 11:13
  • @WhozCraig I was asking if there was a way to init multidimensional arrays using the '[first ... last] = value' syntax - the code I posted was just an example of using this syntax with a standard array. Thanks all for correcting my mistake though. – Liam Lacey Dec 05 '14 at 11:45
  • Not exactly a duplicate but answers the question: http://stackoverflow.com/questions/21528288/c-structure-array-initializing – Lundin Dec 05 '14 at 12:18

1 Answers1

5

The initialization you use isn't standard C, it's a GCC extension (Designated Initializers).

To initialize a 3d array, use:

int array[10][10][10] = {[0 ... 9] [0 ... 9] [0 ... 9] = 42};

Demo.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294