2017-03-25 5 views
0

私は順序付けされたint配列のすべての置換をリストし、各置換を使用することを意図したCコードをいくつか持っていますが関数が意図したとおりに動作しますが、これまでprintf( "\ n")を削除したときに気付いていました。メインでは、プログラムは動作しますが、停止しません。それで、それは正常に動作します。コードは以下の通りです。誰が私に何が起こっているのか理解するのを助けることができますか?cプログラムコードは新しい行を印刷せずにループを停止しません

#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; 
    } 

} 
+2

'inDecOrder'は' int inDecOrder = 1; 'のように初期化します – BLUEPIXY

+0

[コンパイラの警告を有効にしてエラーとして扱います。](http://coliru.stacked-crooked.com/a/ddaf7de1df80c3fa) – WhozCraig

+0

、ありがとう。 – yenchy1

答えて

0

stdioライブラリバッファの出力と、それのいずれかが改行出力ストリームで文字(「\ n」)、またはときに、明示的にfflush()関数を呼び出すが発生した場合にのみ、実際のためにそれを書き出します。

関連する問題