我正在编写一个 C 程序,其中使用 6 个变量 a、b、c、d、e、f
a,b,c 是常量值,我应该从命令行作为参数传递。
d,e,f 将是结构数组的大小。
typedef struct
{
blah blah
} ex;
ex ex0[d];
我对如何将所有这些作为参数传递感到非常困惑。现在我已经硬编码了这些值,显然我不应该这样做。
我正在编写一个 C 程序,其中使用 6 个变量 a、b、c、d、e、f
a,b,c 是常量值,我应该从命令行作为参数传递。
d,e,f 将是结构数组的大小。
typedef struct
{
blah blah
} ex;
ex ex0[d];
我对如何将所有这些作为参数传递感到非常困惑。现在我已经硬编码了这些值,显然我不应该这样做。
这应该让你开始:
int main(int argc, char* argv[]) {
// argc - number of command line arguments
// argv - the comand line arguments as an array
return 0;
}
您传递给程序的所有参数都存储在 main 函数的第二个参数中
int main(int argc, char* argv[]) // or int main(argc, char** argv)
因此您可以通过 argc[3] 轻松访问第 4 个参数。但它不是int,是string,所以需要解析。有一些标准库可用于从 argc 获取实际参数并将它们解析为您需要的类型。但是在休闲程序中使用它们是没有意义的,因此您的代码可能如下所示:
typedef struct
{
blah blah
} ex;
int main(int argc, char* argv[])
{
ex ex0[(int)argv[3]]; // i am not sure if it works on pure C, so you can try int atoi(char *nptr) from stdlib.h
}
使用命令行参数
int main(int argc, char* argv[]) // or int main(int argc, char **argv)
{
// argc is the argument count
//argv : The array of character pointers is the listing of all the arguments.
//argv[0] is the name of the program.
//argv[argc] is a null pointer
}