ikraduya edian
ikraduya edian

Reputation: 80

Can we use dynamic array data() as a longopts parameter in getopt_long function?

I am trying to create an argument parsing class on C++ that will be using getopt_long function. So basically I want the longopts argument can be created dynamically.

This code, that using static array for longopts argument will work:

int main(int argc, char **argv) {
  while (true) {
    static struct option long_options_static[] = {
      {"a", required_argument, 0, 'a'},
      {"b", required_argument, 0, 'b'},
    };
    int option_index = 0;
    char c = getopt_long(argc, argv, "", long_options_static, &option_index);
  }
  return 0;
}

But this, that using std::vector will compile but not work as expected:

int main(int argc, char **argv) {
  while (true) {
    std::vector<struct option> long_options_vect(2);
    long_options_vec[0] = {"a", required_argument, 0, 'a'};
    long_options_vec[1] = {"b", required_argument, 0, 'b'};
    int option_index = 0;
    char c = getopt_long(argc, argv, "", long_options_vect.data(), &option_index);
  }
  return 0;
}

From the getopt_long manual, it only stated that

longopts is a pointer to the first element of an array of struct option...

So in theory, using any kind of containers such as std::vector or std::array and then passing the storage's pointer is possible right? But I get unrecognized option error, am I missing something?

Upvotes: 2

Views: 110

Answers (1)

NicholasM
NicholasM

Reputation: 4673

The array needs to include a special sentinel value to indicate its end. Otherwise, getopt_long cannot know how many elements are in the array. From the linked man page:

The last element of the array has to be filled with zeros.

Upvotes: 2

Related Questions