Specifying &debug
in longopts
doesn't store the integer value of the option to the specified address, getopt_long
expects you to extract integer values yourself.
According to the manual, the int *flag
member of struct option
does something completely different:
flag
"specifies how results are returned for a long option. [If non-NULL],getopt_long()
returns 0, and flag points to a variable which is set toval
if the option is found, but left unchanged if the option is not found.
You specify &debug
for flag
and 'd'
for val
, so debug
gets set to 'd'
(the number 100) when --debug
is specified. Since you're already storing the result of getopt_long
into the opt
variable, you don't need to store &debug
in longopts
at all. Instead, use the optarg
variable to get the argument to --debug
:
case 'd':
debug = atoi(optarg);
switch (debug) {
...