从C中的文件读取时出现Seg Fault

ple*_*ood 1 c file segmentation-fault fault

我只是尝试使用3个命令行参数运行此程序:2个int和1个文件名.

我一直在运行我的程序:

a.out 1 2 devices.txt
Run Code Online (Sandbox Code Playgroud)

devices.txt看起来像这样:

1
Run Code Online (Sandbox Code Playgroud)

我的主要方法如下:

int main(int argc, char* argv[]){
int MaxIterations, T, numDevices;
FILE *devices;

printf("Num arguments: %d \n", argc);
if(argc < 3 || argc > 4){
    printf("ERROR, need exactly 2 or 3 arguments!\n");
    return 1;
} else if (argc == 3){

    MaxIterations = argv[1]; // max iterations allowed
    T = argv[2]; // time interval
    devices = fopen("devices.in", "r");
} else {


    MaxIterations = argv[1];
    T = argv[1];
    devices = fopen(argv[3], "r");
    if(devices == NULL){
        fprintf(stderr, "CANT OPEN FILE: %s!\n", argv[3]);
        exit(1);
    }


}

FILE* file = fopen ("devices.txt", "r");
 int i = 0;

fscanf(devices, "%d", numDevices);
printf("Number of devices: %d \n", numDevices);

fclose(devices);
return 0;
Run Code Online (Sandbox Code Playgroud)

}

我错误的是给了我一个段错误?我添加了debug printf来确定seg故障实际触发的位置,它看起来像是:

fscanf(devices, "%d", numDevices);
Run Code Online (Sandbox Code Playgroud)

oua*_*uah 6

启用编译器警告:

这是无效的:

fscanf(devices, "%d", numDevices);
Run Code Online (Sandbox Code Playgroud)

这是你想要的:

fscanf(devices, "%d", &numDevices);
Run Code Online (Sandbox Code Playgroud)

d转换说明符需要指向有符号整数的指针.您传递了(未初始化的)对象的值numDevices.