简体   繁体   中英

first element of the array gets updated when updating the last element

WeightArray holds weights of the values in valueArray. This code finds the maximum value that has a total weight of maxWeight (4 in this case). This code seems to work till the maxWeight = 3. Beyond that there is this weird behavior. In the debugger mode I saw that the output array K[0] gets updated when i =4, j = 0. Can I someone point me what's the mistake I am making.

void Knapsack_Repetition(int *val, int *weight, int len, int B)
{
    int K[B+1];
    int S[len];
    int remW;

    K[0] = 0;
    S[0] = 0;
    for(int i = 1; i <= B; i++)
    {
    K[i] = 0;
    for(int j = 0; j < len; j++)
    {
        if(weight[j] <= i)
        {
            remW = i - weight[j];
            if ((K[i] < (val[j] + K[remW])))
            {
                K[i] = (val[j] + K[remW]);
                S[i] = val[j]; // use it to trace back the values
            }

        }
    }
}
printf("%d\n",K[B]);
free(val);
free(weight);
}
int main(void) {

    int valueArray[] = {10,40,50,70};
    int weightArray[] = {1,3,4,5};
    int maxWeight = 4;
    Knapsack_Repetition(valueArray, weightArray, (sizeof(valueArray)/sizeof(valueArray[0])), maxWeight);
}

You can safely expect an undefined behaviour, len is 4 and you are accessing S[4] in some cases here

            if ((K[i] < (val[j] + K[remW])))
            {
                K[i] = (val[j] + K[remW]);
                S[i] = val[j]; // use it to trace back the values
            }

What is specifically happening in your case, is that - since K and S are allocated on the stack, they are very likely contiguous in memory. Remember that the stack grows backwards.

Changing S[4] seems to be changing K[0] because S[4] doesn't exist and the next thing in memory is as you guessed it, K . C allows you to do this, it also allows you to set your neighbourhood on fire!

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