1

我只是想用 3 个命令行参数运行这个程序:2 个整数和 1 个文件名。

我一直在运行我的程序:

a.out 1 2 devices.txt

devices.txt 看起来像这样:

1

我的主要方法如下所示:

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;

}

我做错了什么导致我出现段错误?我添加了调试 printf 来确定 seg 错误实际触发的位置,它看起来像它:

fscanf(devices, "%d", numDevices);
4

2 回答 2

6

启用编译器警告:

这是无效的:

fscanf(devices, "%d", numDevices);

这里是你想要的:

fscanf(devices, "%d", &numDevices);

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

于 2013-02-06T20:51:08.277 回答
0

问题是 fscanf 函数需要一个指向存储从文件读取的值的变量的指针。你需要类似的东西

fscanf(devices, "%d", &numDevices);

您收到段错误的原因是,在您的原始代码中,numDevices 的(未初始化的)值被用作要写入的地址 - 而且由于它不太可能是有效的可写地址,段错误是通常的方式你的电脑说“不!” :)

于 2013-02-06T21:01:03.103 回答