C 中 main 的参数

发布于 2024-10-02 12:26:16 字数 100 浏览 5 评论 0原文

我不知道该怎么办!我对 C 基础知识有很好的了解。结构、文件 IO、字符串等。除了 CLA 之外的所有内容。由于某种原因我无法理解这个概念。任何建议、帮助或建议。 PS我是linux用户

I don't know what to do! I have a great understanding of C basics. Structures, file IO, strings, etc. Everything but CLA. For some reason I cant grasp the concept. Any suggestions, help, or advice. PS I am a linux user

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

十秒萌定你 2024-10-09 12:26:16

main 的签名是:

int main(int argc, char **argv);

argc 指传入的命令行参数的数量,其中包括所调用的程序的实际名称由用户。 argv 包含实际参数,从索引 1 开始。索引 0 是程序名称。

因此,如果您像这样运行程序:

./program hello world

那么:

  • argc 将为 3。argv
  • [0] 将为“./program”。
  • argv[1] 将是“你好”。
  • argv[2] 将是“世界”。

The signature of main is:

int main(int argc, char **argv);

argc refers to the number of command line arguments passed in, which includes the actual name of the program, as invoked by the user. argv contains the actual arguments, starting with index 1. Index 0 is the program name.

So, if you ran your program like this:

./program hello world

Then:

  • argc would be 3.
  • argv[0] would be "./program".
  • argv[1] would be "hello".
  • argv[2] would be "world".
凉风有信 2024-10-09 12:26:16

想象一下这样

*main() is also a function which is called by something else (like another FunctioN)

*the arguments to it is decided by the FunctioN

*the second argument is an array of strings

*the first argument is a number representing the number of strings

*do something with the strings

也许一个示例程序会有所帮助。

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

    printf("you entered in reverse order:\n");

    while(argc--)
    {
        printf("%s\n",argv[argc]);
    }

return 0;
}

它只是以相反的顺序打印您作为参数输入的所有内容,但您应该创建新的程序来执行更有用的操作。

编译它(就像说你好)从终端使用参数运行它

./hello am i here

,然后尝试修改它,以便它尝试检查两个字符串是否彼此相反,那么您将需要检查 argc 参数是否恰好为 3其他任何内容都会打印错误

if(argc!=3)/*3 because even the executables name string is on argc*/
{
    printf("unexpected number of arguments\n");
    return -1;
}

,然后检查 argv[2] 是否与 argv[1] 相反
并打印结果

./hello asdf fdsa

应该输出

they are exact reverses of each other

最好的例子是文件复制程序尝试它就像 cp cp

file1 file2

cp 是第一个参数(argv[0] 而不是 argv[1]) 并且大多数情况下你应该忽略第一个参数,除非你需要参考资料或者其他东西,

如果你制作了 cp 程序,你真的理解了主要参数......

Imagine it this way

*main() is also a function which is called by something else (like another FunctioN)

*the arguments to it is decided by the FunctioN

*the second argument is an array of strings

*the first argument is a number representing the number of strings

*do something with the strings

Maybe a example program woluld help.

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

    printf("you entered in reverse order:\n");

    while(argc--)
    {
        printf("%s\n",argv[argc]);
    }

return 0;
}

it just prints everything you enter as args in reverse order but YOU should make new programs that do something more useful.

compile it (as say hello) run it from the terminal with the arguments like

./hello am i here

then try to modify it so that it tries to check if two strings are reverses of each other or not then you will need to check if argc parameter is exactly three if anything else print an error

if(argc!=3)/*3 because even the executables name string is on argc*/
{
    printf("unexpected number of arguments\n");
    return -1;
}

then check if argv[2] is the reverse of argv[1]
and print the result

./hello asdf fdsa

should output

they are exact reverses of each other

the best example is a file copy program try it it's like cp

cp file1 file2

cp is the first argument (argv[0] not argv[1]) and mostly you should ignore the first argument unless you need to reference or something

if you made the cp program you understood the main args really...

沙沙粒小 2024-10-09 12:26:16

为了在 posix 系统上解析命令行参数,标准是使用 getopt() 系列库例程来处理命令行参数。

一个很好的参考是 GNU getopt 手册

For parsing command line arguments on posix systems, the standard is to use the getopt() family of library routines to handle command line arguments.

A good reference is the GNU getopt manual

静谧幽蓝 2024-10-09 12:26:16

Siamore,我不断看到每个人都使用命令行来编译程序。我通过 code::blocks 使用 ide 中的 x11 终端,code::blocks 是我的 linux 机器上的 gnu gcc 编译器。我从未从命令行编译过程序。

因此,如果我希望程序名称为 cp,我是否将 argv[0]="cp"; Cp 初始化为字符串文字。任何发送到 stdout 的内容都会在命令行上进行???我明白你举的例子了!尽管你输入的字符串只有几个字长,但它仍然只是一个参数。因为它是用双引号括起来的。所以 arg[0] ,程序名称,实际上是带有换行符的字符串文字?所以我明白为什么你使用 if(argc!=3) 打印错误。因为 prog name = argv[0] 并且之后还有 2 个参数,并且不再发生错误。

我还有什么理由使用它呢?我真的认为我对如何从命令行或终端编译缺乏了解是我在这方面缺乏了解的原因! Siamore,你帮助我更好地理解了课堂!仍然不完全理解,但我并没有忘记这个概念。我将学习从终端进行编译,然后重新阅读您写的内容。我敢打赌,到时候我就彻底明白了!有了你的更多帮助,哈哈

<>
代码不是我自己写的,而是来自我的书。

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;

    printf("The following arguments were passed to main(): ");
    for(i=1; i<argc; i++) printf("%s ", argv[i]);
    printf("\n");

    return 0;
} 

这是输出:

anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hey man
The follow arguments were passed to main(): hey man
anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hi how are you doing?
The follow arguments were passed to main(): hi how are you doing?

所以 argv 是字符串文字表,argc 是字符串文字的数量。现在 argv[0] 是
程序的名称。因此,如果我输入 ./CLA 来运行程序,./CLA 就是 argv[0]。以上
程序将命令行设置为接受无限数量的参数。我可以将它们设置为
如果我愿意,只需要 3 或 4 个。就像一个例子或你的例子所示,Siamore... if(argc!=3) printf("Some error gone here");

谢谢 Siamore。没有你们我不可能做到这一点,感谢其他人付出的时间和努力!

PS,万一将来出现这样的问题...你永远不知道哈哈,问题是因为我使用的是 IDE
又名代码::块。如果我要运行上面的程序,它将打印该程序的路径/目录。

示例:~/Documents/C/CLA.c 它必须从终端运行并使用命令行进行编译。 gcc -o CLA main.c 并且您必须位于该文件的目录中。

Siamore, I keep seeing everyone using the command line to compile programs. I use x11 terminal from ide via code::blocks, a gnu gcc compiler on my linux box. I have never compiled a program from command line.

So if I want the programs name to be cp, do I initialize argv[0]="cp"; Cp being a string literal. And anything going to stdout goes on the command line??? I understood the example you gave! Even though the string you entered was a few words long, it was still only one arg. Because it was encased in double quotations. So arg[0], the prog name, is actually your string literal with a new line character?? So I understand why you use if(argc!=3) print error. Because the prog name = argv[0] and there are 2 more args after that, and anymore an error has occurred.

What other reason would I use that? I really think that my lack of understanding about how to compile from the command line or terminal is my reason for lack understanding in this area!! Siamore, you have helped me understand cla's much better! Still don't fully understand but I am not oblivious to the concept. I'm gonna learn to compile from the terminal then re-read what you wrote. I bet, then I will fully understand! With a little more help from you lol

<>
Code that I have not written myself, but from my book.

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;

    printf("The following arguments were passed to main(): ");
    for(i=1; i<argc; i++) printf("%s ", argv[i]);
    printf("\n");

    return 0;
} 

This is the output:

anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hey man
The follow arguments were passed to main(): hey man
anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hi how are you doing?
The follow arguments were passed to main(): hi how are you doing?

So argv is a table of string literals, and argc is the number of them. Now argv[0] is
the name of the program. So if I type ./CLA to run the program ./CLA is argv[0]. The above
program sets the command line to take an infinite amount of arguments. I can set them to
only take 3 or 4 if I wanted. Like one or your examples showed, Siamore... if(argc!=3) printf("Some error goes here");

Thank you Siamore. I couldn't have done it without you, and thank you everyone else for their time and effort!

PS in case there is a problem like this in the future...you never know lol the problem was because I was using the IDE
AKA Code::Blocks. If I were to run that program above it would print the path/directory of the program.

Example: ~/Documents/C/CLA.c it has to be ran from the terminal and compiled using the command line. gcc -o CLA main.c and you must be in the directory of the file.

久伴你 2024-10-09 12:26:16

Main 就像任何其他函数一样,argc 和 argv 就像任何其他函数参数一样,不同之处在于 main 是从 C 运行时调用的,并将参数传递给 main,但是 C 运行时是在 c 库中定义的,您无法修改它因此,如果我们确实在 shell 上或通过某些 IDE 执行程序,我们需要一种机制将参数传递给 main 函数,以便您的 main 函数可以根据您的参数在运行时表现不同。参数是 argc ,它给出参数的数量,而 argv 是指向指针数组的指针,它将值保存为字符串,这样你就可以传递任意数量的参数而不限制它,这是实现 var args 的另一种方式。

Main is just like any other function and argc and argv are just like any other function arguments, the difference is that main is called from C Runtime and it passes the argument to main, But C Runtime is defined in c library and you cannot modify it, So if we do execute program on shell or through some IDE, we need a mechanism to pass the argument to main function so that your main function can behave differently on the runtime depending on your parameters. The parameters are argc , which gives the number of arguments and argv which is pointer to array of pointers, which holds the value as strings, this way you can pass any number of arguments without restricting it, it's the other way of implementing var args.

任性一次 2024-10-09 12:26:16

对 @anthony 代码做了一个小小的更改,这样我们就可以获得带有参数编号和值的格式良好的输出。当您有多个参数时,以某种方式更容易阅读输出:

#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("The following arguments were passed to main():\n");
    printf("argnum \t value \n");
    for (int i = 0; i<argc; i++) printf("%d \t %s \n", i, argv[i]);
    printf("\n");

    return 0;
} 

并且输出类似于:

The following arguments were passed to main():
0        D:\Projects\test\vcpp\bcppcomp1\Debug\bcppcomp.exe
1        -P
2        TestHostAttoshiba
3        _http._tcp
4        local
5        80
6        MyNewArgument
7        200.124.211.235
8        type=NewHost
9        test=yes
10       result=output

Had made just a small change to @anthony code so we can get nicely formatted output with argument numbers and values. Somehow easier to read on output when you have multiple arguments:

#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("The following arguments were passed to main():\n");
    printf("argnum \t value \n");
    for (int i = 0; i<argc; i++) printf("%d \t %s \n", i, argv[i]);
    printf("\n");

    return 0;
} 

And output is similar to:

The following arguments were passed to main():
0        D:\Projects\test\vcpp\bcppcomp1\Debug\bcppcomp.exe
1        -P
2        TestHostAttoshiba
3        _http._tcp
4        local
5        80
6        MyNewArgument
7        200.124.211.235
8        type=NewHost
9        test=yes
10       result=output
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文