C语言中argc与argv怎么用?为什么我初始化argc时候老是出错??

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

argc与argv[]是启动C程序时系统传入的,可以直接使用。argc是参数数量,argv是参数表数组。如命令行为“prg.exe 1 2 3”,则argc为4,argv[0]="prg.exe",argv[1]="1",argv[2]="2",argv[3]="3"。以下是LCC-WIN32模板文件(加了一行显示所有参数语句):
/* --- The following code comes from e:\lcc\lib\wizard\textmode.tpl. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void Usage(char *programName)
{
fprintf(stderr,"%s usage:\n",programName);
/* Modify here to add your usage message when the program is
* called without arguments */
}

/* returns the index of the first argument that is not an option; i.e.
does not start with a dash or a slash
*/
int HandleOptions(int argc,char *argv[])
{
int i,firstnonoption=0;

for (i=1; i< argc;i++) {
if (argv[i][0] == '/' || argv[i][0] == '-') {
switch (argv[i][1]) {
/* An argument -? means help is requested */
case '?':
Usage(argv[0]);
break;
case 'h':
case 'H':
if (!stricmp(argv[i]+1,"help")) {
Usage(argv[0]);
break;
}
/* If the option -h means anything else
* in your application add code here
* Note: this falls through to the default
* to print an "unknow option" message
*/
/* add your option switches here */
default:
fprintf(stderr,"unknown option %s\n",argv[i]);
break;
}
}
else {
firstnonoption = i;
break;
}
}
return firstnonoption;
}

int main(int argc,char *argv[])
{
if (argc == 1) {
/* If no arguments we call the Usage routine and exit */
Usage(argv[0]);
return 1;
}
/* handle the program options */
HandleOptions(argc,argv);
/* The code of your application goes here */

for (int i=0;i<argc;i++)printf("%s ",argv[i]);

return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-06-18
都是main函数的参数,解释如下:
argc:命令行总的参数的个数,即argv中元素的格式。
*argv[
]:字符串数组,用来存放指向你的字符串参数的指针数组,每一个元素指向一个参数。
argv[0]:指向程序的全路径名。
argv[1]:指向在DOS命令行中执行程序名后的第一个字符串。
argv[2]:指向第二个字符串。
第2个回答  2016-01-07
C语言带参数定义形式为
int main(const int argc, const char *argv[]);
其中的参数argc和argv并不是在main函数中进行初始化使用的,而是用来从命令行传递参数。
1 argc,命令行传递参数的总个数。
2 argv,命令行传递的每个参数值。

例如,编译得到的exe文件为a.exe,执行
a.exe 1 123 asdgf 34
时,每个参数均会转为字符串形式,存储于argv中,这时
argc = 5
argv = {"a.exe", "1", "123", "asdgf", "34"}
第3个回答  2015-10-29
1、main是个函数,argc、argv是输入的参数,但是和一般的函数又不太一样,这里argc(argument count :参数个数)argv(argument vector(大概是):指针数组,指向参数内容)。
2、例如:argc至少为1,这是ex后没有任何参数,argv[0]指向ex程序的路径如E:\ex.exe;
ex abcd efg h3 k44,有4个参数,加上默认的共有5个参数,分别如下:
argv[0] 指向路径E:\ex.exe;\
argv[1] 指向字符串"abcd"
argv[2] 指向字符串"efg"
argv[3] 指向字符串"h3"
argv[4] 指向字符串"k44"
相似回答