Search code examples
carraysloopsprintfvariable-length-array

printf changes my output


I'm trying to solve this challenge on Hackerrank.

I've reached a problem where I cannot proceed, but I can't see where I've gone wrong - and I'm hoping someone here can help.

My current solution is as follows:

int main() {

    int n,k,p,count,total; 
    int t[n];
    scanf("%d %d",&n,&k);
    for(int i = 0; i < n; i++){
        scanf("%d",&t[i]);
    }
    p = 1;
    total=0;
    for(int x = 0; x < n; x++){
        for(int j = 1; j <= t[x]; j++, count++){
            if(count>k){
                count = 1;
                p++;
            }
            if(j==p){
                total++;
            }
            //printf("j: %d p: %d\tcount: %d\n",j,p,count);
        }
        p++;
        count=1;
    }
    printf("%d",total);

    return 0;
}

The printf that I have commented out is what changes my eventual output. For example, with an input of:

10 5

3 8 15 11 14 1 9 2 24 31

I should be getting an answer of 8. If I un-comment that printf() function, then I can see the current problem number and page number to see if it's 'special'. If I leave it un-commented, my eventual output is 8, which is what I want. But I don't want all the iterations printed out as well. The problem I have is that when I remove that line, or comment it out, the output becomes 5, not 8. What is causing this to change?


Solution

  • In your code, while defining int t[n];, you're using n uninitialized. That , invokes undefined behavior.

    To elaborate, n is an automatic local variable that is not initialized explicitly, so the content of that variable is indeterminate. Attempt to use an indeterminate value leads to UB.

    Quoting C11, chapter §6.7.9

    If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. [...]

    and, annex §J.2, undefined behavior,

    The value of an object with automatic storage duration is used while it is indeterminate

    You need to move the definition of int t[n]; after you have successfully scanned the value from the user. Check the return value of scanf() to ensure the success.