Reputation: 455
Is there a way to determine the number of message
elements in the following look-up table or do I need to explicitly have an int size
in the struct?
typedef struct {
int enable;
char* message[3];
} lookuptable;
lookuptable table[] = {
{1, {"Foo", "Bar", "Baz"}}, // # 3
{1, {"Foo", "Bar"}}, // # 2
{1, {"Foo"}}, // # 1
{1, {"Foo", "Baz"}}, // # 2
};
Upvotes: 0
Views: 428
Reputation: 126408
There will always be exactly 3 message elements in the message array, because you have defined it as having a size of 3. Those elements of the array you don't initialize will be initialized to NULL, so you can loop through the initialized (non-null) elements with:
lookuptable *table_entry = ...
for (int i = 0; i < 3 && table_entry->message[i]; i++) {
...do something...
It might be a good idea to replace the constant 3
with a #define
constant, so it only exists in one place. Or you could use the sizeof(array)/sizeof(array[0])
trick:
for (int i = 0; i < sizoef(table_entry->message)/sizeof(table_entry->message[0]) && table_entry->message[i]; i++)
Upvotes: 1
Reputation:
No there is no way to do that. You will have to store the number of elements somewhere or terminate the array with a magic number or a NULL.
Upvotes: 3