尝试使用 C++ 克隆“yes”命令作为一个小实验(这是在 Ubuntu 12.10 上),这里有一个小问题:
#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;
}
如果我保持原样,我会收到标题中描述的警告。如果我删除 argv 上的星号之一,我会收到有关将“char*”转换为“char**”的错误。并删除额外的功能(即将其全部放在 main 中,就像这样):
int main(int argc, char** argv) {
if ( argv != NULL ) {
while (true) {
cout << argv[1] << endl;
}
} else {
while (true) {
cout << "y" << endl;
}
}
return 0;
}
对警告没有影响。
在此先感谢...
最佳答案
您可以编写 char **argv
或 char *argv[]
但不能同时使用双星号和双括号。
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 typeint
, 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. Ifargc
is nonzero these arguments shall be supplied inargv[0]
throughargv[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 ofargv[argc]
shall be 0.
关于c++ - 警告 : second argument of ‘int main(int, char***)’ should be ‘char **’ [-Wmain] (GNU C++ compiler; Ubuntu 12. 10),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14450653/