fflush(stdin) 的工作如何改变下面代码中的输出?

How is the working of fflush(stdin) changing the output in below code?

#include <stdio.h>
int main()
{
        int test_no ,count=1,i,n,j;
        scanf("%d",&test_no);
        fflush(stdin);
        int arr1[test_no];
        for(i=0;i<test_no;i++)
        {
                scanf("%d",&n);
                printf("\n");
                int arr[n];
                for(j=0;j<n;j++)
                {
                        fflush(stdin);
                        scanf("%d",&arr[i]);
                }
                for(j=1;j<=n-1;j++)
                {
                        if(arr[j-1]>arr[j])
                        {
                                count++;
                        }
                }
                if(n==1)
                {
                        arr1[i]=1;
                }
                else
                {
                        arr1[i]=count;
                }
                count=1;
        }
        for(i=0;i<test_no;i++)
        {
                printf("%d\n",arr1[i]) ;
        }
        return 0;
}

这个解决方案就是针对这个problem

我没有得到第三种情况所需的输出,它给我的输出为 3 或 4,具体取决于我是将 fflush(stdin) 放在 scanf("%d",arr[i]) 之前还是在 scanf("%d",arr[i]) 之后,请告诉这个代码的问题。

没有 一些神奇的方式。

首先,fflush(stdin); 调用 undefined behavior不要使用那个。

引用 C11,章节 §7.21.5.2,fflush 函数强调我的

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

也就是说,

for(j=0;j<n;j++)
{
    fflush(stdin);
    scanf("%d",&arr[i]);
}

对我来说看起来很不对, arr[i] 不能保证在范围内。应该是

scanf("%d",&arr[j]);