简体   繁体   中英

Pass argv to function: error: array type 'char *[]' is not assignable

I want to let a sub class to handle the command line arguments but get error: array type 'char *[]' is not assignable .

I have tried assignment with * and & and also looked getoption_long()

#include <stdio.h>
class {
public:
  void setParam(int _argc, char *_argv[]) {
    argc = _argc;
    argv = _argv; // something wrong here
  }
  void show(void) {
    int i = 0;
    while (++i < argc)
      printf("Arg #%d %s\n", i, argv[i]);
  }
private:
  int argc;
  char *argv[];
} sp;
int main (int argc, char *argv[]) {
  sp.setParam(argc, argv);
  sp.show();
  return 0;
}

Compile is done with:

clang -o showparam showparam.cpp

According to C++ standard arrays are not assignable because they are non-modifiable lvalue.

If you want to copy pointer to your arguments array to argv parameter of sp class change this parameter type to char** argv;

You might want to consider a more modern datatype for storing the args inside your class. std::vector would be a possibility for this, which brings some additional value and safety. A modified version of your code might look like this:

#include <stdio.h>
#include <vector>
class {
public:
  void setParam(int _argc, char *_argv[]) {
    argv.assign( _argv, _argv+_argc );
  }
  void show(void) {
    int i = 0;
    while (++i < argv.size())
      printf("Arg #%d %s\n", i, argv[i]);
  }
private:
  std::vector<char*> argv;
} sp;
int main (int argc, char *argv[]) {
  sp.setParam(argc, argv);
  sp.show();
  return 0;
}

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