简体   繁体   中英

what does a const char** look like?

I have a class which takes the main command line arguments (eg, -B, -a, etc) and does something with them, but also i would like to be able to instantiate that function without passing the command line arguments, so for example:

constructor:

myClass(int argc, const char **argv){
    <initialise class with flags from argv>
}

myClass() : myClass(2, "-B") {}
}

Here i am trying to instantiate myClass with the flag "-B", but it keeps giving me the error:

no known conversion for argument 3 from 'const char [3]' to 'const char**'

so i was wondering what i need to do to pass a value in as const char**?

First level is pointer to first pointer to char * . Second level is pointer to the first const char of c-string.

> cdecl explain "const char ** args"
declare args as pointer to pointer to const char

If you have -std=c++11 available, you can use this example (but it can be rewritten to use old standard):

#include <iostream>
#include <vector>
#include <string>    

class test {
  public:
    test(const std::vector<std::string> & args) {
      for (auto & arg : args) {
        std::cout << arg << "\n";
      }
    }

    test() : test{{"-B"}} {}
};

int main(int argc, const char ** argv) {
  test sth{{argv+1, argc+argv}}; // skip program name here
  test sth_else;

}

const char** is pointer to const char* . In your case, you intend to pass multiple arguments as part of argv , so you can pass something like below:

const char* argv[] = {"<program name>", "B"};
myClass m(2, argv);

Note: const char** x & const char* x[] are same. The 2nd syntax is helpful when one wants to "represent" an array.

Here I am giving a way to mimic the main(int, char**) function argument for your internal test. If you want to pass from default constructor to argument constructor then all the above stuff will have to go global.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM