reggaeguitar
reggaeguitar

Reputation: 1804

Getting different answer on Windows vs Linux

I'm trying to solve this problem https://www.hackerrank.com/challenges/flowers When I run my code in Visual Studio 2013 on Windows 7 on my machine I get the correct answers but on the site (I'm pretty sure they use Linux and I'm positive this is the compiler they use gcc 4.9.2, C99 standard) I get very large numbers for answers, specifically 12588576 (instead of 13) for the first test case and 1395920336 (instead of 15) for the second test case. I'm guessing it has something to do with the qsort call.

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

int comp_desc(const void * a, const void * b)
{
    int * aPtr = (int*)a;
    int * bPtr = (int*)b;
    return *bPtr - *aPtr;
}

int main()
{
    int flowersNeeded, numFriends, i;
    scanf("%d %d", &flowersNeeded, &numFriends);
    getchar();
    int flowerCosts[100];
    memset(flowerCosts, 0, 100);
    for (i = 0; i < flowersNeeded; ++i)
    {
        scanf("%d", &flowerCosts[i]);
    }
    qsort(flowerCosts, 100, sizeof(int), comp_desc);
    int flowersBought = 0;
    int moneySpent = 0;
    int multiplier = 1;
    for (i = 0; i < flowersNeeded; ++i)
    {
        moneySpent += flowerCosts[i] * multiplier;
        multiplier = (++flowersBought / numFriends) + 1;
    }
    printf("%d\n", moneySpent);
    return 0;
}

Upvotes: 0

Views: 328

Answers (1)

interjay
interjay

Reputation: 110128

memset(flowerCosts, 0, 100);

The 100 should be sizeof(flowerCosts). The 100 doesn't fill the whole array because it's the size in bytes.

qsort(flowerCosts, 100, sizeof(int), comp_desc);

You probably want to sort only the entries you filled in (flowersNeeded) rather than all 100 of them.

As a result of these two bugs, you're sorting garbage values in the uninitialized part of your array.

Upvotes: 5

Related Questions