0

有没有办法确定message以下查找表中的元素数量,还是我需要int size在结构中明确包含一个?

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
};
4

2 回答 2

3

不,没有办法做到这一点。您必须将元素的数量存储在某处,或者用幻数或 NULL 终止数组。

于 2013-06-30T14:30:47.207 回答
1

消息数组中总是正好有 3 个消息元素,因为您已将其定义为大小为 3。您未初始化的数组元素将被初始化为 NULL,因此您可以循环遍历已初始化的(非-null) 元素:

lookuptable *table_entry = ...
for (int i = 0; i < 3 && table_entry->message[i]; i++) {
    ...do something...

3用常量替换常量可能是个好主意#define,因此它只存在于一个地方。或者你可以使用这个sizeof(array)/sizeof(array[0])技巧:

for (int i = 0; i < sizoef(table_entry->message)/sizeof(table_entry->message[0]) && table_entry->message[i]; i++)
于 2013-06-30T18:46:51.403 回答