'How to initialize only few elements of an array with some values?
Is it possible to assign some values to an array instead of all? To clarify what I want:
If I need an array like {1,0,0,0,2,0,0,0,3,0,0,0} I can create it like:
int array[] = {1,0,0,0,2,0,0,0,3,0,0,0};
Most values of this array are '0'. Is it possible to skip this values and only assign the values 1, 2 and 3? I think of something like:
int array[12] = {0: 1, 4: 2, 8: 3};
Solution 1:[1]
Is it possible to skip this values and only assign the values 1, 2 and 3?
In C, Yes. Use designated initializer (added in C99 and not supported in C++).
int array[12] = {[0] = 1, [4] = 2, [8] = 3};  
Above initializer will initialize element 0, 4 and 8 of array array with values 1, 2 and 3 respectively. Rest elements will be initialized with 0. This will be equivalent to  
 int array[12] = {1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0};   
The best part is that the order in which elements are listed doesn't matter. One can also write like
 int array[12] = {[8] = 3, [0] = 1, [4] = 2}; 
But note that the expression inside [ ] shall be an integer constant expression.
Solution 2:[2]
Here is my trivial approach:
int array[12] = {0};
array[0] = 1; array[4] = 2; array[8] = 3;
However, technically speaking, this is not "initializing" the array :)
Solution 3:[3]
An alternative way to do it would be to give default value by memset for all elements in the array, and then assign the specific elements:
int array[12];
memset(array, 0, sizeof(int) * 12); //if the default value is 0, this may not be needed
array[0] = 1; array[4] = 2; array[8] = 3;
Solution 4:[4]
Standard C17
The standard (C17, N2176) has an interesting example in § 6.7.9(37):
EXAMPLE 13 Space can be “allocated” from both ends of an array by using a single designator:
int a[MAX] = { 1, 3, 5, 7, 9, [MAX-5] = 8, 6, 4, 2, 0 };In the above, if
MAXis greater than ten, there will be some zero-valued elements in the middle; if it is less than ten, some of the values provided by the first five initializers will be overridden by the second five.
Example
#include <stdio.h>
#define MAX 12
int main(void)
{
    // n2176, § 6.7.9(37)
    int a[MAX] = {
        1, 3, 5, 7, 9, [MAX-5] = 8, 6, 4, 2, 0
    };
    for (size_t i = 0; i < MAX; i++) {
        printf("%d\n", a[i]);
    }
    return 0;
}
Output:
1
3
5
7
9
0  <-- middle element, defaults to zero
0  <-- middle element, defaults to zero
8
6
4
2
0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Ian | 
| Solution 4 | Daniel | 
