Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why struct option array needs an addtional dummy entry when using getopt_long

For example the option array is:

static struct option const long_options[] =
{
  {"help", no_argument, 0, 'h'},
  {"version", no_argument, 0, 'v'},
  {0, 0, 0, 0}
};

Is it for padding?

like image 861
Oxdeadbeef Avatar asked Dec 16 '10 20:12

Oxdeadbeef


2 Answers

Look at the man page for getopt_long():

int
 getopt_long(int argc, char * const *argv, const char *optstring,
     const struct option *longopts, int *longindex);

The argc and argv pair show one way to say how many entries there are in an array (by explicit count, though since argv[argc] == 0, there is also a sentinel there). The optstring indicates short arguments; the longindex is an output parameter. That leaves only the pointer longopts which means that the function must be able to tell how many entries are in the array without any supporting count (there is no longoptcount argument), so the end of the array is marked by all values zero - a sentinel value.

like image 191
Jonathan Leffler Avatar answered Oct 17 '22 07:10

Jonathan Leffler


It's a 'sentinel' so the code processing the array knows when it's gotten to the end.

like image 23
Michael Burr Avatar answered Oct 17 '22 06:10

Michael Burr