DEV Community

Arrays in C

mikkel250 on December 19, 2019

Creating and using arrays In C, once you create an array, the type and size must be declared, and those values are immutable. In other w...
Collapse
 
demiaus profile image
demiaus

Very useful! Assigning by index was news to me.

I think both of those float array comments have too many elements, no?

float myArray[4] = {[2] = 500.5, [1] = 300.0, [0] = 100.0};
// results in array [100.0, 300.0, 500.5, 0, 0]
Enter fullscreen mode Exit fullscreen mode

and

float myArray[10] = {[2] = 500.5, 300.0, [7] = 100.0};
//results in array [0, 0, 0, 500.5, 300.0, 0, 0, 0, 100.0, 0, 0]
Enter fullscreen mode Exit fullscreen mode

I think this bit is a little misleading:

If elements are not assigned, they will be set to 0.

That is true, if some/any of the elements are assigned. But if the local array is only declared, like

int array[5];
Enter fullscreen mode Exit fullscreen mode

the values are garbage. On the other hand, if the array is declared globally outside of all functions, the values actually are implicitly initialized to 0 even if no value is assigned.

There is no shortcut to assign all elements to the same value like some other languages provide.

I just learned that there is a very naughty non-standard way to do that like this:

int array[10] = {[0 ... 4] = -1};
// [-1, -1, -1, -1, -1, 0, 0, 0, 0, 0]
Enter fullscreen mode Exit fullscreen mode

where you give a range of indices and the value you want to set those to.
But not all compilers support it, and ISO C forbids it, so probably better not to get used to it and just use loops like you said.

Collapse
 
deciduously profile image
Ben Lovy

Huh, TIL float myArray[4] = {[2] = 500.5, [1] = 300.0, [0] = 100.0};. Good to know, thanks for the write-up.