循环固定大小的数组没有用C确定其大小 [英] Looping a fixed size array without defining its size in C

查看:93
本文介绍了循环固定大小的数组没有用C确定其大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一些示例code键启动问题:

 的#define FOO_COUNT 5 静态为const char * foo的[] = {
       123,
       456,
       789
       987
       654
 };

这通常会被迭代,作为一个例子的方式,如下:

  INT I = FOO_COUNT;
而(--i> = 0){
 的printf(%S \\ n,foo的[I]);

反正有做上面没有明确具有人类算上5号?在将来,我可能会添加/删除元素,却忘了更新数组的大小,从而打破我的应用程序。


解决方案

  INT I = sizeof的(富)/ sizeof的(富[0]);

Some example code to start the question:

 #define FOO_COUNT 5

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

The way this would normally be iterated over, as for one example, is the following:

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

Is there anyway to do the above without explicitly having the human count the number 5? In the future I might add/remove elements and forget to update the size of the array, thus breaking my app.

解决方案

int i = sizeof(foo)/sizeof(foo[0]);

这篇关于循环固定大小的数组没有用C确定其大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆