简体   繁体   English

扫描以获取多个用户输入

[英]Scanf for multiple user inputs

Apologizes I am very inexperienced with C. I have the following code: 抱歉,我对C缺乏经验。我有以下代码:

char * a[BUF_SIZE]; 

scanf("%d", numberOf);
do {
    a[i] = (char *)malloc(MAX_LINE_LEN + 1);
    scanf("%s", a[i]);
    ++i;
} while(i < numberOf);

The idea is simple, read two inputs from stdin using scanf, the first being a single int, followed by some array of strings. 这个想法很简单,使用scanf从stdin读取两个输入,第一个是单个int,然后是一些字符串数组。 Scanf works independently in both cases eg scanf("%d", numberOf) will store a digit and scanf("%s", a[i]) will store a set of strings into the array. Scanf在这两种情况下均独立工作,例如scanf(“%d”,numberOf)将存储一个数字,而scanf(“%s”,a [i])将一组字符串存储到该数组中。 However in conjunction reading an integer first into numberOf causes a segfault when reading in a set of strings. 但是,在读取一组字符串时,先将整数读入numberOf会导致段错误。 My question is why? 我的问题是为什么? I know its generally bad practice to use scanf, but I fail to see how reading in multiple inputs from stdin can cause a segfault in the resulting code. 我知道使用scanf通常是不好的做法,但是我看不到从stdin读取多个输入会如何导致结果代码出现段错误。 Much Thanks! 非常感谢!

From the code, it looks like numberOf is an int . 从代码numberOf是一个int When using scanf , you want to pass it a pointer, so change scanf("%d", numberOf); 使用scanf ,要向其传递一个指针,因此更改scanf("%d", numberOf); to scanf("%d", &numberOf); scanf("%d", &numberOf);

What scanf does is take the user input and put it into the memory address specified by the second parameter. scanf作用是接受用户输入,并将其放入第二个参数指定的内存地址中。 When you provide an int as the second parameter, scanf tries to put user input into a memory address (specified by the int ) that it may not own, causing the seg-fault. 当您提供int作为第二个参数时, scanf尝试将用户输入放到它可能不拥有的内存地址(由int指定)中,从而导致seg-fault。

You are missing & operator in scanf("%d", numberOf); 您在scanf("%d", numberOf);中缺少&运算符scanf("%d", numberOf); put it as &numberOf 放在&numberOf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM