jakes
jakes

Reputation: 2095

loop condition with variable input with scanf - C

#include <stdio.h>
#include <stdlib.h>

int main() {
    unsigned int n0;

    scanf("%d", &n0);
    const unsigned int n = n0;
    short unsigned int A[n];
    short unsigned int d, x, y, k;
    short int l, r;
    int i, j;

    for (i = 0; i < n; i++) {
        scanf("%d", &A[i]);
    }

    scanf("%d", &d);
    for (i = 1; i <= d; i++) {
        scanf("%d %d", &x, &y);
    }
    return 0;
}

Hi, I'm a total newbie with C and stumbled across a situation that amazed me a lot. In the above code, I would like to ask the user to input some number d, and then to input d pairs of point coordinates. But to my surprise the program ends executing after inputting first pair of (x,y), no matter what value of d greater than 1 is input first. It doesn't happen if I assign value to d in code (e.x. d = 5;). What may be the reason? Is the value assigned to the variable via the scanf statement somehow different and cannot be used in a loop condition?

Upvotes: 2

Views: 522

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727057

Pay attention to the warnings that you get when compiling your code. One of the warnings should be as follows:

a.c:19:12: warning: format specifies type 'int *' but the argument has type
     'unsigned short *' [-Wformat]
scanf("%d",&d);
      ~~  ^~
      %hd

Using %d causes scanf cast a pointer to short as a pointer to int, leading to undefined behavior. It looks like in your case the upper portion of an int gets stored in a short, while the bottom portion gets dropped. For numbers undef 216 the upper part is zero, so the subsequent loop iterates zero times.

Fixing all warnings will eliminate this problem

scanf("%hu", &d);
... // Fix other scanf calls as well.

Note: There is no good reason for making loop variables short.

Upvotes: 1

Related Questions