warning: second argument of ‘int main(int, char***)’ should be ‘char **’ [-Wmain] (GNU C++ compiler; Ubuntu 12.10)

17.6k Views Asked by At

Trying to clone the "yes" command using C++ as a little experiment (this is on Ubuntu 12.10), and there's a little problem here:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>

using namespace std;

void yes (char* cmd[]) {
  if ( cmd != NULL ) {
    while (true) {
      cout << cmd[1] << endl;
    }
  } else {
    while (true) {
      cout << "y" << endl;
    }
  }
}

int main(int argc, char** argv[]) {
  yes(argv[1]);
  return 0;
}

If I leave it as is, I get the warning as described in the title. If I remove one of the asterisks on argv, I get an error about converting "char*" to "char**". And removing the extra function (i.e. putting it all in main, like so):

int main(int argc, char** argv) {
  if ( argv != NULL ) {
    while (true) {
      cout << argv[1] << endl;
    }
  } else {
    while (true) {
      cout << "y" << endl;
    }
  }
  return 0;
}

makes no difference about the warning.

Thanks in advanced...

4

There are 4 best solutions below

0
On

The 2nd parameter to main is an array of C- Strings, containing the options you pass in, so it should be char*argv[] or char **.

Take a look at the liveworkspace snippet

0
On

You can write char **argv or char *argv[] but not both double-star and double-brackets.

ISO/IEC 14882:2011 §3.6.1 Main function

An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:

int main() { /* ... */ }

and

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

In the latter form argc shall be the number of arguments passed to the program from the environment in which the program is run. If argc is nonzero these arguments shall be supplied in argv[0] through argv[argc-1] as pointers to the initial characters of null-terminated multibyte strings (NTMBSs) (17.5.2.1.4.2) and argv[0] shall be the pointer to the initial character of a ntmbs that represents the name used to invoke the program or "". The value of argc shall be non-negative. The value of argv[argc] shall be 0.

0
On

Remove the brackets from argv on main:

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

AND from cmd on yes

void yes (char* cmd) {
0
On

Seems like the first answer nailed it. Long story short, it wasn't the removal of the "yes" function (and subsequent merge of its code into main) OR the removal of one of the asterisks (i.e. "char* argv" instead of "char** argv"), but a combination of both that removed the warning (simply removing one of the asterisks with the function still in place caused a conversion error).

Thanks again!