简体   繁体   中英

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?

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.

数组必须具有固定的大小,您可以在使用calloc(),malloc()读取元素数量n后创建

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