tags:

views:

67

answers:

4

Hello,

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_details; i++)
{
    printf("Name: [ %s ] [ %s ]\n", emp_details[i].name, emp_details[i].data);
}
+2  A: 

Should be:

for(i=0; emp_details[i].name != NULL; i++) { 
    printf("Name: [ %s ] [ %s ]\n", emp_details[i].name, emp_details[i].data); 
}
sharptooth
+2  A: 

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)

iWerner
+3  A: 

I suggest:

for ( i=0 ; emp_details[i].name != NULL ; i++)
{
    // do something
}
mouviciel
nice and simple :)
warren
+4  A: 

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.

Chris Jefferson
May I suggest using `->` instead of `(* ).` ?
mouviciel
In addition to using `->` instead of `(* ).` don't forget to check for `it->data != NULL` before trying to use it. Otherwise "john" may well cause `printf()` (or whatever) to crap out.
Michael Burr
@Chris Jefferson Any reason why `int size_of_array = sizeof(emp_details)/sizeof(details_t);` fragile ? any personal experience you want to share?
vinit dhatrak