C iterate array of struct
arrays, c, struct
Solution
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);
}
Problem
say I have declare a 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 } ``` 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. 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" .