簡體   English   中英

c程序代碼在不打印新行的情況下不會停止循環

[英]c program code does not stop looping without printing a new line

我有一些C代碼,旨在列出有序int數組的所有排列,然后使用每個排列(就目前而言,我只是打印它們),但我注意到,盡管該功能按預期工作,但每次刪除的printf( “\\ n”); 基本上,該程序可以運行,但不會停止。 有了它,就可以正常工作。 代碼如下。 誰能幫助我了解發生了什么。

#include <stdio.h>
#include <stdlib.h>
#define ARRAYSIZE 4

int nextPermutation (int array[], int arraySize);

int main()
{
    int *array = calloc(ARRAYSIZE,sizeof(int)),i;

    for(i=0; i<ARRAYSIZE; i++)
    {
        array[i]=i+1;
    }

    while(nextPermutation(array,ARRAYSIZE))
    {

        for(i=0; i<ARRAYSIZE; i++)
        {
            printf("%d ",array[i]);
        }
        printf("\n");

    }

    return 0;
}

int nextPermutation(int array[], int arraySize)
{

    int maxElement=arraySize,i,maxElementIndex,inDecOrder;

    //check to see if the array is in descending order
    for(i=0; i<arraySize-1; i++)
    {
        if(array[i]<array[i+1])
        {
            inDecOrder = 0;
            break;
        }
    }
    //if the array is in descending order then return 0
    if(inDecOrder)return 0;
    //find the index of the max element.
    for(i=0; i<arraySize; i++)
    {
        if(array[i]==maxElement)
        {
            maxElementIndex = i;
            break;
        }
    }

    if(maxElementIndex!=0)
    {
        //if the max element is not in the first index then move it left and get next permutation
        array[i]=array[i-1];
        array[i-1]=maxElement;
        return 1;

    }
    else
    {
        //if the max index is in the first index then create an array without the max index
        int *newArray = calloc(arraySize-1,sizeof(int));

        //copy the elements from the first array into the new array with out the max element and get next permutation
        for(i=1; i<arraySize; i++)
        {
            newArray[i-1]=array[i];
        }
        nextPermutation(newArray,arraySize-1);
        for(i=0; i<arraySize-1; i++)
        {
            array[i]=newArray[i];
        }
        array[arraySize-1]=maxElement;
        return 1;
    }

}

stdio庫將緩沖輸出,並且僅在輸出流中遇到換行符('\\ n')或顯式調用fflush()函數時才將其真正寫出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM