在“加速的C++:实例实用编程”中,它说
现在我们了解了指针和字符数组,我们可以了解如何将参数传递给主函数。如果main函数愿意接受,大多数操作系统都提供一种将字符串序列作为参数传递给main的方法。主要作者表达这种意愿的方式是提供两个主要参数:一个int和一个指向char指针的指针。像任何参数一样,它们可以具有任意名称,但是程序员经常将它们称为argc和argv。 argv的值是一个指向指针数组初始元素的指针,每个参数一个。 argc的值是数组中argv指向初始元素的指针的数量。该数组的初始元素始终代表调用程序的名称,因此argc始终至少为1。自变量(如果有)占据数组的后续元素。
举例来说,该程序将其参数(如果有的话)之间留有空格:
int main(int argc, char** argv) {
// if there are arguments, write them if (argc > 1) {
int i;
// declare i outside the for because we need it after the loop finishes
for (i = 1; i < argc-1; ++i)
cout << argv[i] << " ";
cout << argv[i] << endl;
return 0;
}
// write all but the last entry and a space // argv[i] is a char*
// write the last entry but not a space
我不明白的是这句话“argc的值是数组中argv指向初始元素的指针的数目。该数组的初始元素始终代表程序被调用的名称,因此argc始终至少为1。argv [0]是什么?
最佳答案
argc
的值不能为负,但可以为0,这意味着没有参数传递给程序。但是,从reference
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) ([multibyte.strings]) and argv[0] shall be the pointer to the initial character of a ntmbs that represents the name used to invoke the program or "".
因此,在这种情况下,
argv[0]
是用于调用程序的名称,或者是一个空字符串。
关于c++ - 将数组参数传递给主函数索引始于1 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63120441/