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
CodePudding user response:
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;
CodePudding user response:
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;
}