如何在 C 中获取命令行参数的值



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

命令行参数: $ ./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()方法。所有这些都给了我分段错误。

检查是否提供了所有参数argc

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

最新更新