解析 main 函数中的参数 int argc, char *argv[]
有时会见到C/C++中 main
函数中写了参数 int argc, char *argv[]
。
这两个参数的含义如下:
argc
:传入main
函数的字符串个数argv
:传入main
函数的字符串
例程
// test.c
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("numOfArgc = %d\n\n", argc);
printf("numOfArgv = %lu\n\n", sizeof(*argv));
for(int i = 0; i <= argc; i++){
printf("argv[%d] = %s\n", i, argv[i]);
}
return 0;
}
编译运行:
betty@betty-VirtualBox:~/桌面/TEST/test$ gcc test.c -o target
betty@betty-VirtualBox:~/桌面/TEST/test$ ./target what a nice day!
numOfArgc = 5
numOfArgv = 8
argv[0] = ./target
argv[1] = what
argv[2] = a
argv[3] = nice
argv[4] = day!
说明在命令行输入的所有内容会被存储到 argv
数组中,但 argc
并不是这个 argv
数组的长度,其长度为8,且具有默认值
// test.c
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("numOfArgc = %d\n\n", argc);
printf("numOfArgv = %lu\n\n", sizeof(*argv));
for(int i = 0; i < sizeof(*argv); i++){//注意循环条件
printf("argv[%d] = %s\n", i, argv[i]);
}
return 0;
}
编译运行:
betty@betty-VirtualBox:~/桌面/TEST/test$ ./target
numOfArgc = 1
numOfArgv = 8
argv[0] = ./target
argv[1] = (null)
argv[2] = SHELL=/bin/bash
argv[3] = COLORTERM=truecolor
argv[4] = TERM_PROGRAM_VERSION=1.74.2
argv[5] = LANGUAGE=zh_CN:zh
argv[6] = PWD=/home/betty/桌面/TEST/test
argv[7] = LOGNAME=betty
标签:argc,int,argv,betty,test,main
From: https://www.cnblogs.com/3to4/p/17041600.html