Looping through an array of structs
I have this structure and I thought I could set the condition if the structure is pointing to a NULL value.
Here is my simple structure for this example:
typedef struct
{
char *name;
char *data;
} details_t;
details_t emp_details [] =
{
{ "peter", "lawyer" },
{ "john", NULL }, /* No data for john */
{ NULL, NULL }, /* Indicates last element in the array */
};
I think I should be increment the emp_details array and dereferencing the pointer to see if it contains a NULL in the first array element. But not sure if I am going in the right direction.
for(i=i; *emp_det开发者_如何学运维ails; i++)
{
printf("Name: [ %s ] [ %s ]\n", emp_details[i].name, emp_details[i].data);
}
There are two different ways you could handle this look, and you've kind of overlapped them both!
I'm assuming you want to stop when 'name' is NULL.
for(details_t* it = emp_details; (*it).name != NULL; it++)
{ printf("..", (*it).name, (*it).data); }
or:
for(int i = 0; emp_details[i].name != NULL; i++)
{ printf("..", emp_details[i].name, emp_details[i].data); }
There is one other alternative. You could not a NULL at the end, and get the size of emp_details by doing:
int size_of_array = sizeof(emp_details)/sizeof(details_t);
However, I would personally advise against this, as I find it fragile in practice.
I suggest:
for ( i=0 ; emp_details[i].name != NULL ; i++)
{
// do something
}
Should be:
for(i=0; emp_details[i].name != NULL; i++) {
printf("Name: [ %s ] [ %s ]\n", emp_details[i].name, emp_details[i].data);
}
What you need is:
for(i=i; emp_details[i].name; i++)
{
printf("Name: [ %s ] [ %s ]\n", emp_details[i].name, emp_details[i].data);
}
(This assumes that emp_details[i].data
is allowed to be NULL, as in your array initialization)
精彩评论