ç迭代结构数组 [英] C iterate array of struct
本文介绍了ç迭代结构数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有一个声明结构
struct mystruct {
char a[10];
double b;
}
struct mystruct array[20] = {
{'test1',1.0},
{'test2',2.0} <---- I just want to declare 2 items first because I am going to add new ones later.
};
int i;
for( i=0; array[i].a != NULL ;i++){
.... <--- so here I just want to display what is initialized first
}
然而,在for循环显示过去的2个项目(即20个项目,但所有其余的都是垃圾)。我只是想显示目前只什么被初始化,即使我宣布以存储其中的20。怎么做?谢谢。
However, the for loop display past the 2 items ( ie to 20 items but all the rest are garbage ). I just want to display currently only what is initialized, even though i declared to store 20 of them. How to do it? thanks.
我使用C90标准。
此外,假设我在加入未来更多的项目,但仍比少20个项目,我想只是想显示,直到这是有效的最后一个项目。
I am using C90 standard. Also, let's say I added more items in future , but still lesser than 20 items, i would just want to display until the "last item that is valid" .
推荐答案
有关编译器将接受初始化语法(这应该是任何标准的C编译器),你应该能够这样写:
For compilers that will accept the initializer syntax (that should be any standard C compiler), you should be able to write:
struct mystruct
{
char a[10];
double b;
}; // semi-colon added!
struct mystruct array[20] =
{
{ "test1", 1.0 }, // character strings!
{ "test2", 2.0 },
};
enum { ARRAY_SIZE = sizeof(array) / sizeof(array[0]) };
int i;
for (i = 0; i < ARRAY_SIZE && array[i].a[0] != '\0'; i++)
{
printf("[%s] => %f\n", array[i].a, array[i].b);
}
这篇关于ç迭代结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文