2013-04-11 5 views
0

문제가 있습니다. 내 프로그램은 DEV C++에서 제대로 작동하는 것으로 보이지만 마지막 For 루프는 Xcode에서 언제 멈출지를 알지 못합니다. 어떤 도움?컴파일러에서 루프 문제가 발생했습니다.

#include <stdlib.h> 
#include <stdio.h>   
#include <time.h> 
#include <string.h>   

void strip_newline(char *str,int size) 
{ 
    int i; 
    for(i=0;i<size;++i) 
    { 
     if(str[i]=='\n') 
     { 
      str[i]='\0'; 
      return; 
     } 
    } 
} 

int main()  
{ 
    int randomnumber; 
    int max;   
    int tall;   
    char name[40][tall]; 
    char seat[40][tall]; 
    int count;   
    int currentcount; 
    int flag; 

    srand(time(NULL)); 
    printf("Enter total number of students: "); 
    scanf("%d",&max); 
    getchar();   
    tall=max+1;  
    randomnumber=rand()% max +1; 
    printf("This is your random number\n %d \n",randomnumber); 
    printf("Enter your students names and press enter after each name:\n "); 

    fgets(name[0],40,stdin); 
    strip_newline(name[0],40); 

    for(count=1; count < max; count++) 
    {  
     printf("Please enter next name\n "); 
     fgets(name[count],40,stdin); 
     strip_newline(name[count],40); 
    } 

    count=-1; 

    do { 
     randomnumber=rand()% max; 
     flag=0; 
     for(currentcount=0; currentcount<max; currentcount++) 
     { 
      if(strcmp(name[randomnumber],seat[currentcount])==0) 
      { 
       flag=1; 
      } 
      else 
      { 
      } 
     } 
     if(flag==0) 
     { 
      strcpy(seat[count],name[randomnumber]); 
      count++; 
     } 
     else 
     { 
     } 
    } 
    while (count != max); 

    for(count=0; count < max; count++) 
    { 
     printf("%s sits in seat %d\n",seat[count],count+1); 
    } 

    getchar(); 
    return 0; 
} 
+2

불필요한 줄 바꿈이 코드를 만들 것 : 또한, 당신이 그들을 사용하는 방법 주어진, 당신은 당신이 치수를 교환 할 필요가 있으므로, 40 자, tall 문자의하지 (40) 배열의 tall 배열을 원하는 것 같다 훨씬 더 읽기 쉽습니다. –

+0

코드가 ... 형식이 다릅니다. 앞으로는 사람들에게 더 쉽게 이것을 고려해보십시오. 복잡한 코드를 읽는 것보다 코드를 포맷 할 시간을 가진 사람을 돕는 것이 더 쉽습니다. 또한, 어떤 입력에 어려움이 있습니까? 모두들? 그들 중 일부는? 그들은 무엇인가? 또한 프로그램을 C의 80 줄보다 버그를 나타내는 최소 크기로 줄이는 것을 고려하십시오. –

+2

그 원인인지는 모르겠지만 'name'과 'seat'이 선언 된 시점에서 'tall'은 초기화되지 않았으므로 배열의 크기를 알 수 없습니다. 또한,'fgets (name [0], 40, stdin);'는 char name [some_dim] [40];을 원한다. –

답변

1

귀하의 문제는이 라인에 있습니다 tall

int tall;   
char name[40][tall]; 
char seat[40][tall]; 

가 초기화되지 않습니다 (값을 제공하지), 당신 (40 개) 배열이 될 것입니다 얼마나 큰지 알 수 없습니다. 그것은 행동이 공식적으로 정의되지 않았기 때문에 0과 매우 큰 숫자 사이의 어떤 것이라도 될 수 있습니다. 나중에 tall으로 할당해도 배열이 마술처럼 크기가 조정되지는 않습니다.

해결 방법은 크기에 대한 충분한 정보가있을 때까지 배열이 선언되지 않도록 코드를 다시 정렬하는 것입니다. 당신의 들여 쓰기를 정리

//... 
printf("Enter total number of students: "); 
scanf("%d",&max); 
getchar();   
tall=max+1;  
char name[tall][40]; 
char seat[tall][40]; 
//... 
+0

대단히 감사합니다. – Tohrik

관련 문제