I want to get a filename from a commandline argument so I can pass it to a file-opening function, however, argv[] seems to be of type const char ** by default, even if it was defined as "const char * argv[]" in the main's arguments. My function requires const char *, is there a way to convert this two, or something?
int main(int argc, const char *argv[]) {
memory Memory;
Memory.loadROM(argv); // Error 'argument of type "const char **" is incompatible with parameter of type "const char *"'
}
When used in function parameters without being a reference type, const char *argv[]
and const char **argv
is exactly identical because the former will be adjusted to the latter.
Per N4296, Section 8.3.5p5:
any parameter of type “array of T” or “function returning T” is adjusted to be “pointer to T” or “pointer to function returning T,” respectively
So const char *argv[]
is "an array of type const char *
" and is thus adjusted to "a pointer to const char *
".
And since argv
is of type const char **
, you want to dereference it to get a const char *
:
Memory.loadROM(argv[1])
argv
contains an array of char *
, so if you only want one, simplify specify which you want:
Memory.loadROM(argv[1]);
Read here for more on what'll be in argv
.
The difference between char* argv[]
and char** argv
is actually pretty subtle, so you'll often see them used interchangeably. The typical default is char** argv
since that's more conventional, yet the alternative isn't wrong.
In both cases argv[0]
is the first argument. Remember that pointers act like arrays and char* argv[]
is an array of char*
.
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.