gpt4 book ai didi

c - 使用命令行将参数传递给主函数,但值始终为 2

转载 作者:行者123 更新时间:2023-11-30 19:54:01 25 4
gpt4 key购买 nike

这是我的主要功能代码

os2.c

#include <stdio.h>
int main( int argc, char *argv[]){
int item;
item = argc;
printf("%d", item);

return 0;
}

I run the following command line in Ubuntu's terminal

gcc -o 测试 os2.c
./测试5

打印的结果等于2而不是5,我的代码有什么问题吗?

最佳答案

首先,你的问题不仅仅针对 Ubuntu/Linux。
它也适用于 Windows 和 Macintosh,包括使用终端的每个操作系统。

argc = 参数计数:传递给程序的参数数量
argv = 参数 vector :传递的参数

argc 是一个 int,用于计算命令行参数。

I run the following command line in Ubuntu's terminal: gcc -o test os2.c
./test 5

这里是你的论据

  1. argv[0] == ./test
  2. argv[1] == 5

因此我们得出结论:

argc 根据上面的参数数量为 2。
argv 包含我们传递给程序的参数。

这是如何正确使用参数的示例:

来源.c

#include <stdio.h>

int main(int argc, char **argv){
for(int i = 0;i < argc;i++)
printf("arg %d : %s\n",i,argv[i]);

return 0;
}

命令行

gcc -o test source.c
./test this is a test

输出

arg 0 : ./test
arg 1 : this
arg 2 : is
arg 3 : a
arg 4 : test

但无论如何,我建议永远不要使用第一个参数;这将是您的软件中的一个漏洞,因为它很容易被黑客攻击。在 C 中,有很多方法可以做任何您想做的事情。

现在;如果您想要获取值 5 而不是计算您传递的参数数量,您应该知道必须做什么到您的应用程序,在 OP 情况下为 2

关于c - 使用命令行将参数传递给主函数,但值始终为 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45931976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com