Oxdeadbeef
Oxdeadbeef

Reputation: 1063

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?

Upvotes: 5

Views: 1455

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753675

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.

Upvotes: 3

Michael Burr
Michael Burr

Reputation: 340208

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

Upvotes: 3

Related Questions