Question

I'm trying to do the most basic of things and am hitting a brick wall. I'm trying to read in a file name from the command line to use later in my program, but I can't even seem to extract the name from argv[]. Here's the code:

#include <iostream>
#include <string.h>

using namespace std;

int main(int argc, char **argv[]){
    cout << "argc = " << argc << "\n\n";
    cout << "Filename: " << argv[1] << "\n";
    return 0;
}

I'm testing it on inputs that supply an argument of course, since there's no error checking. Here's what I get when I run the program:

./a.out testfilename

*

argc = 2

Filename: 0x7fff56e41d30

Now I understand argv[1] is a pointer to an array of chars, so this output makes sense. However, if I make the following change,

cout << "Filename: " << argv[1] << "\n";

to

cout << "Filename: " << *argv[1] << "\n";

in an attempt to dereference argv[1] to pull out the actual string, I get a segmentation fault..

Was it helpful?

Solution

int main(int argc, char *argv[]){

or

int main(int argc, char **argv){

but not

int main(int argc, char **argv[]){

OTHER TIPS

That should be:

int main(int argc, char *argv[])
                        ^ only one * here
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top