循环固定大小的数组而不在C中定义其大小

ran*_*its 6 c loops

一些示例代码来启动问题:

 #define FOO_COUNT 5

 static const char *foo[] = {
       "123",
       "456",
       "789",
       "987",
       "654"
 };
Run Code Online (Sandbox Code Playgroud)

通常迭代的方式,如一个例子,如下:

int i = FOO_COUNT;
while (--i >= 0) {
 printf("%s\n", foo[i]);
Run Code Online (Sandbox Code Playgroud)

反正有没有明确让人数统计5?将来我可能会添加/删除元素而忘记更新数组的大小,从而破坏我的应用程序.

aJ.*_*aJ. 16

int i = sizeof(foo)/sizeof(foo[0]);
Run Code Online (Sandbox Code Playgroud)


Ign*_*ams 12

最后使用一个标记,例如NULL:

static const char *foo[] = {
       "123",
       "456",
       "789",
       "987",
       "654",
       NULL
};

for (char *it = foo[0]; it != NULL; it++)
{
        ...
}
Run Code Online (Sandbox Code Playgroud)