【问题标题】:How to get value of a command line argument in C [SOLVED]如何在 C 中获取命令行参数的值 [已解决]
【发布时间】:2021-07-22 04:39:27
【问题描述】:

我正在编写一个程序,我需要在其中获取第二个命令行参数的值,以便稍后确定要使用的算法。

命令行参数:$ ./project2 FIRSTFIT 268435456 testfile.txt

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
//~~~~~~~~~~~~~~~~ Main
int main(int argc, char *argv[])
{
    /*
     Reading in the parameters from command line
     argv[0] = the program
     argv[1] = the type of memory allocation algorithm to use
     argv[2] = N = total memory allocation
     argv[3] = script file (.txt)
     */
    char* memAlgoType = (char*)argv[1];
    int totalMemAlloc = atoi(argv[2]);
    FILE* file;
    file = fopen(argv[3], "r");
    
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ First fit
    if(strcmp(memAlgoType, "FIRSTFIT") == 0)
    {
        //code for first fit algorithm here
    }
}

当我这样做时,我收到分段错误(核心转储)错误,并且在我的 XCode IDE 上,我在使用 strcmp() 时收到 EXC_BAD_ACCESS 错误

我已尝试将我的代码修改为 char memAlgoType = (char)argv[1][0]; 以仅比较第一个字符 我试过strcpy(memAlgoType, argv[1]),也试过memcpy()方法。所有这些都给了我分段错误。

我不知道从这里做什么......

感谢您的帮助!

【问题讨论】:

  • 您应该在尝试使用argv之前检查argc
  • 如果您实际上没有传递命令行参数,就会发生您遇到的错误。
  • 您的程序对我来说运行良好(当我添加缺少的右括号时)。这是您正在测试的完整程序吗?如果没有,错误可能在您遗漏的部分;在这种情况下,minimal reproducible example 是必不可少的。
  • 当你直接从 XCode IDE 运行时,你可能没有任何命令行参数

标签: c segmentation-fault command-line-arguments


【解决方案1】:

如果提供了所有参数,请检查 argc

注意:int totalMemAlloc = atoi(argv[2]); 处理大量数字可能很危险。

【讨论】:

  • 要检查 argc,我是否只需做一个 if 语句来查看 argc > 0 吗?
  • 不,您需要检查用户是否提供了足够的参数。 argc > 0 检查用户是否提供了至少 1 个参数。
  • argc > 0 检查用户是否提供了至少 0 个参数。
猜你喜欢
  • 2015-12-24
  • 1970-01-01
  • 2016-01-11
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
  • 1970-01-01
  • 2019-06-09
  • 2012-06-20
相关资源
最近更新 更多