0

The below code behaves as if I have initialized variable res to 0, if I uncomment the lines above the first time I used it.

int t, mi,cur,n,res;

scanf("%d",&t);
while(t-- && scanf("%d",&n) == 1)
{
    for (int i = 1; i <= n; ++i)
    {
        scanf("%d",&h[i]);
    }
    for (int i = 1; i <= n; ++i)
    {
        scanf("%d",&k[i]);
    }

    for (int i = 0; i < 1001; ++i)
        dp[0][i] = INF;
    for (int i = 0; i < 501; ++i)
        dp[i][0] = 0;


    for (int i = 1; i <= n; ++i)
    {
        for (int j = 1; j <= 2*n; ++j)
        {
            dp[i][j] = dp[i-1][j];
            if(j >= k[i-1])
                dp[i][j] = min(dp[i-1][j],1 + dp[i][j-k[i-1]]);
        }
    }
    // The lines below.
    //for (int i = 0; i <= n; ++i)
    //{
    //  for (int j = 0; j <= 2*n; ++j)
    //  {
    //      printf("%d ", dp[i][j]);
    //  }
    //  printf("\n");
    //}

    for (int i = 1; i <= n; ++i)
    {
        res += dp[n][2*h[i]];
    }
    printf("%d\n", res);

When I print the value of res with the lines commented, it gives me garbage value, but when I uncomment it, it gives me the expected value. I don't know the advanced concepts of the language. Why this happens?

phraniiac
  • 384
  • 1
  • 3
  • 16
  • 3
    I believe that there is no guarantee as to what the value of `res` will be if you don't initialize it. So it _might_ be equal to `0`, or really anything else. Don't rely on it in any case. – Tim Biegeleisen Oct 26 '15 at 04:44
  • Your code definitely exhibits symptoms of undefined behavior. The use of `int i = 1; i <= n; ++i` points the use of wrong indices and accessing arrays out of bounds. Please post a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). That will be very helpful in diagnosing the problem more precisely. – R Sahu Oct 26 '15 at 04:45

1 Answers1

0

dp[0][*] and dp[*][0] are not initialized as you fill your array starting at index 1.

Then, if h[i] is 0, you will definitely copy an unitialized value to res.

The advanced concepts of the language in this case is just that uninitialized variables leads to undefined behaviour and should not be used. See Default variable value (as commented by Kelvin Lai).

So you may accept that and don't try to figure out why printing the values fix the problem....because there is no point trying to determine how undefined behaviours are working...;-)

Note: The fact that comented lines in your post fixe the problem may be compiler/platform/configuration specific. It's just a kind of corner case that fixes the issue of your uninitialized variables being used when they should not...

Community
  • 1
  • 1
jpo38
  • 20,821
  • 10
  • 70
  • 151