Array initialization

Arrays and collections / Arrays

void printArray(const char *name, const int arr[], size_t count) {
    printf("%s is {", name);
    for (size_t i = 0; i < count; i++) {
        if (i > 0) {
            printf(", ");
        }
        printf("%d", arr[i]);
    }
    printf("}\n");
}

//C has no empty array: the size is fixed when the array is made

//Single-dimensional array
int n1[3] = {1, 2, 3};
int n2[] = {1, 2, 3}; //the compiler counts the size
const char *s1[] = {"1", "2", "3"};
//s1[2] is "3"

//the elements left out are zero
int n3[5] = {1, 2};
//n3 is {1, 2, 0, 0, 0}
int n4[5] = {}; //C23
//n4 is {0, 0, 0, 0, 0}

//elements by index
int n5[5] = {[1] = 10, [3] = 30};
//n5 is {0, 10, 0, 30, 0}

//Multidimensional array
int n6[2][2] = {{1, 2}, {4, 5}};
//without inner braces the elements fill the rows in order
int n7[2][3] = {1, 2, 3, 4, 5, 6};
n7[1][2] = 7;
//n6[1][1] is 5, n7[1][2] is 7

//Jagged array: an array of pointers to rows of different length
int row1[] = {1, 2};
int row2[] = {3, 4, 5};
int *n8[] = {row1, row2};
//n8[1][1] is 4

printArray("n1", n1, 3);
printArray("n2", n2, 3);
printf("s1[2] is %s\n", s1[2]);
printArray("n3", n3, 5);
printArray("n4", n4, 5);
printArray("n5", n5, 5);
printf("n6[1][1] is %d\n", n6[1][1]);
printf("n7[1][2] is %d\n", n7[1][2]);
printf("n8[1][1] is %d\n", n8[1][1]);