[Dimik OJ] Problem 6

Dimik OJ Problem No. 6

Why the loop is running for ones?

#include <stdio.h>
#include<string.h>

int main()
{
    int i, sum, T;
    char N[5];
    scanf("%d", &T);
        for(i = 1; i <= T; i++){
            scanf("%s", N);
            sum = 0;
            sum = (N[0]-'0') + (N[4]-'0');
            printf("Sum = %d\n", sum);
        }

    return 0;
}

This code runs perfectly

int main()
{
    int x, i, sum, T;
    char N[5];
    **scanf("%d", &x);**
    **T = x;**
        for(i = 1; i <= T; i++){
            scanf("%s", N);
            sum = 0;
            sum = (N[0]-'0') + (N[4]-'0');
            printf("Sum = %d\n", sum);
        }

    return 0;
}

You should change this to char N[6];

Because you will be given a number with 5 digits and then there will be the null character (since you are reading the number as a string. So you should have a character array of at least length 6 (i.e. 5 digits + null character).

but when i use x variable for input and assign T = x then the code runs perfect!

scanf(“%d”, &x);
T = x;

This can happen because of how the compiler arranges the variables in memory. It is possible that just by making this change to the code, you are causing the variable T to be stored far from variable N in the memory. And so, when you read N, there is no change of the operation overwriting the value of T.

In C/C++ like programming languages, there is no runtime check for array boundaries. If your memory allocation looked like this:

  N             T
[ _ _ _ _ _ ] [ _ ] 

Here N is of length 5, and you try to read a 5 character string to it, then the null character will end up in the memory location where T is.

Bear in mind that this is just for illustration purpose. You can say this conclusively if you decompile the code and look at the assembly of it.

Nonetheless, the issue with the code is that you didn’t keep sufficient space in the array N and fixing that should fix the issue entirely (without having to rely on hard-to-predict behavior of the compiler).

Thank you so much. :heart_eyes:
Now it’s clear to me. :blush:

1 Like