简体   繁体   中英

Scanf for multiple user inputs

Apologizes I am very inexperienced with C. I have the following code:

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 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. However in conjunction reading an integer first into numberOf causes a segfault when reading in a set of strings. 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. Much Thanks!

From the code, it looks like numberOf is an int . When using scanf , you want to pass it a pointer, so change scanf("%d", numberOf); to scanf("%d", &numberOf);

What scanf does is take the user input and put it into the memory address specified by the second parameter. 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.

You are missing & operator in scanf("%d", numberOf); put it as &numberOf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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