Why int argc, char * argv[] ?

Sep 7, 2012 at 10:36pm
I did copy this from a manual, I confess... but only to test it and see what the content does. And I can not understand this parameter in main int main (int argc, char * argv[]).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main (int argc, char * argv[])
{
    vector<string> Data;
    string Value;

    cout << "Type text and stop with 'end':" << endl;

    // read input
    while ( getline(cin, Value) )
    {
        // are we done?
        if ( Value == "end" )
        {
            // yes
            break;
        }

        // add to vector
        Data.push_back ( Value );
    }

    // iterate
    for ( unsigned int Index = 0; Index < Data.size (); Index++ )
    {
        cout << Index << ": " << Data[Index] << endl;
    }
}


What does int main (int argc, char * argv[]) mean? And char * argv[] looks like a pointer to an array, but what? Why? Where?...

Can I simply remove this parameter and keep on rolling without it? Or does it have to be there?
Last edited on Sep 7, 2012 at 10:37pm
Sep 7, 2012 at 10:40pm
closed account (3hM2Nwbp)
argc is the number of char pointers in the second argument.

argv is an array of char pointers - whose length is that of the first argument, argc.

It's used for receiving program arguments at start-up time.

Alternatively, you can choose to use int main(void) - which is also perfectly valid (if you're not relying program arguments!).

Here's a more in-depth answer:

http://en.wikipedia.org/wiki/Main_function#C_and_C.2B.2B
Last edited on Sep 7, 2012 at 10:41pm
Sep 7, 2012 at 11:00pm
Luc Lieber explained it perfectly. I don't know why the author added that, but I'm sure it's just a habit.

1
2
3
4
5
6
7
8
int main(int agrc, char *arg[]) {
      std::string str;
      getline(std::cin, str);
      std::ofstream writeFile(arg[1]);
      writeFile << str;
      writeFile.close();
      return 0;
}

There's a quick (cheap) example of how command line arguments could/should be used.

It's useless in the code you posted, so it would be best if you just removed it.
Sep 7, 2012 at 11:44pm
The main() function's arguments are to get command line strings from the invoking environment. See here for an example:
http://www.cplusplus.com/forum/beginner/5404/#msg23839

BTW, int main(void) is not valid C++. Use either:

    1. int main()
    2.
int main( int argc, char* argv[] )

A point to keep in mind: the array of char* in the second argument points to non-modifiable data (usually).

Hope this helps.
Last edited on Sep 7, 2012 at 11:44pm
Topic archived. No new replies allowed.