Is it possible to do something like this in C?
Code:
/* This is a NON-WORKING example. It gives a Segmentation Fault. */
const size_t *foos[4] = {
{3, 1, 2, 3},
{4, 10, 20, 30, 40},
{0},
{1, 100}
};
int main () {
size_t i;
for (i = 0; i < 4; i++) {
size_t *f = foos[i];
size_t j;
for (j = f[0]; j > 0; j--) {
printf("%zu ", f[j]);
}
}
return 0;
}
The expected output: 3 2 1 40 30 20 10 100
The intent here is for each array in foos to be allocated by the compiler, and then foos itself would be a 4-element array laid out flatly in memory with each element being the pointer to the first element of its allocated array. In other words, it's a very similar situation to:
Code:
const char *strs[4] = {
"hello",
"world",
"various",
"strings"
};
In this case, the compiler acts exactly as I described, it allocates various char buffers in memory and then strs is 4 consecutive items in memory with each pointing to the first element of its char buffer. Is there not a more general way to do this for any array similar to the syntax I've used above? It is important that the inner arrays are able to be of variable length, just as with a char* array.
Note that I am using the first element of the array to indicate how many elements will be in the array; I'm not asking for any type of bounds checking, only allocation in a manner similar to what is done for arrays of char*.