You can do this by creating an array of pointers. In this case the elements of the jagged array are not necessarily stored contiguously, and the length of the individual rows must be kept somehow so that the jagged array can be used.
If the array type allows it, another option is to use a 2d array, storing the size of each row in the first element of each row. This will likely use more memory than an array of pointers, but the elements will be stored contiguously in memory.
If there is a value that can't appear in the array, a sentinel value can be used instead of explicitly storing the row sizes. This can be used even if the type of the array won't allow storage of size values (e.g., char[][]
).
#include <stdio.h>
#include <string.h>
int main(void)
{
/* Jagged array using pointers */
int array_1[] = { 1, 2, 3 };
int array_2[] = { 5, 6 };
int array_3[] = { 7, 8, 9, 10 };
int *jagged_array_1[] = { array_1, array_2, array_3 };
size_t array_sizes[] = { sizeof array_1 / sizeof *array_1,
sizeof array_2 / sizeof *array_2,
sizeof array_3 / sizeof *array_3 };
for (size_t i = 0; i < 3; i++) {
for (size_t j = 0; j < array_sizes[i]; j++) {
printf("%4d", jagged_array_1[i][j]);
}
putchar('\n');
}
putchar('\n');
/* Using the first element to store sizes */
int jagged_array_2[3][5] = { { 0 } };
jagged_array_2[0][0] = sizeof array_1 / sizeof *array_1;
memcpy(&jagged_array_2[0][1], array_1, sizeof array_1);
jagged_array_2[1][0] = sizeof array_2 / sizeof *array_2;
memcpy(&jagged_array_2[1][1], array_2, sizeof array_2);
jagged_array_2[2][0] = sizeof array_3 / sizeof *array_3;
memcpy(&jagged_array_2[2][1], array_3, sizeof array_3);
for (int m = 0; m < 3; m++) {
for (int n = 0; n < jagged_array_2[m][0]; n++) {
printf("%4d", jagged_array_2[m][n+1]);
}
putchar('\n');
}
putchar('\n');
/* Using a sentinel element */
int jagged_array_3[3][5] = { { 0 } };
memcpy(jagged_array_3[0], array_1, sizeof array_1);
jagged_array_3[0][sizeof array_1 / sizeof *array_1] = -1;
memcpy(jagged_array_3[1], array_2, sizeof array_2);
jagged_array_3[1][sizeof array_2 / sizeof *array_2] = -1;
memcpy(jagged_array_3[2], array_3, sizeof array_3);
jagged_array_3[2][sizeof array_3 / sizeof *array_3] = -1;
for (size_t i = 0; i < 3; i++) {
for (size_t j = 0; jagged_array_3[i][j] != -1; j++) {
printf("%4d", jagged_array_3[i][j]);
}
putchar('\n');
}
putchar('\n');
return 0;
}