gpt4 book ai didi

c - 迭代 argv[] 会产生段错误

转载 作者:太空宇宙 更新时间:2023-11-04 05:53:11 24 4
gpt4 key购买 nike

我正在编写一个从命令行读取“标志”以及程序名称的程序。我希望程序读取多个标志(-i-c-n)并在一个或多个标志组合时执行不同的功能叫做。

这是我开始写的代码:

  printf("Argv 0: %s\n", argv[0]);
printf("Argv 1: %s\n", argv[1]);
printf("Argv 2: %s\n", argv[2]);

for (int i = 1; i <= argc + 1; i++) {
if (strcmp("-i", argv[i]) == 0) {
printf("%s\n", "found -i");
}
else{
printf("%s\n", "did not find -i");
}

}

只是尝试使用一个标志 (-i),但我希望它同时读取一个或多个标志并调用相应的函数。

当我执行程序时:

./program-name test -i
Argv 0: test
Argv 1: -i
Argv 2: (null)
found -i
Segmentation fault

最佳答案

为了简化,argc 是命令行参数的计数,参数保存在argv[] 中。由于 C 数组具有基于 0 的索引,因此在您的代码中,您需要更改

 for (int i = 1; i <= argc + 1; i++)

for (int i = 1; i < argc;  i++)

限制对有效参数列表的访问。

要对此添加一点引用,引用 C11,章节 §5.1.2.2.1,程序启动(强调我的)

If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment. If the value of argc is greater than one, the strings pointed to by argv[1] through argv[argc-1] represent the program parameters.

关于c - 迭代 argv[] 会产生段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34290756/

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