how to iterate over compound literal array?
You cannot.
At least not without providing the additional information on the number of elements the two BookCode
arrays carry, that is 2 and 3. This later info is lost by assigning the two arrays to the pointer-typed elements of MyBooks
. It cannot by calculated any more during run-time.
What you could do is to define a sentinel value and add an instance of such as a stopper element to each BookCode
array's end. This way each array's size can be (re-)calculated during run-time.
This for example can be done like shown below:
#include <stdio.h>
#include <string.h>
typedef struct
{
int book_id;
char value;
} BookCode;
#define BOOKCODE_STOPPER {-1, '\0'}
static const BookCode BookCodeStopper = BOOKCODE_STOPPER;
typedef struct
{
BookCode *codes;
} Books;
size_t get_codes_count(Books * books)
{
BookCode * bc = books->codes;
while (bc->book_id != BookCodeStopper.book_id
&& bc->value != BookCodeStopper.value)
/* doing "while (memcmp(bc, &BookCodeStopper, sizeof BookCodeStopper)" might be faster. */
{
++bc;
}
return bc - books->codes;
}
int main(void)
{
Books books[] = {
{(BookCode[]) {{1, 'a'}, {2, 'b'}, BOOKCODE_STOPPER}},
{(BookCode[]) {{1, 'd'}, {2, 'c'}, {3, 'f'}, BOOKCODE_STOPPER}}
};
size_t n1 = sizeof books / sizeof books[0];
for (size_t i = 0; i < n1; ++i)
{
printf("%zu\n", i);
size_t s = get_codes_count(books + i);
for (size_t j = 0; j < s; ++j)
{
printf("Book code %zu: id=%d, value=%c\n", j, books[i].codes[j].book_id,
books[i].codes[j].value);
}
}
return 0;
}
This approach implies that at least one possible combination of book codes would never appear. In the example above I chose {-1, '\0'}
for this.