2014-11-21 6 views
1

OK, C를 처음 접했고 이것이 작동하지 않는 이유를 알 수 없습니다. 출력은 단지 (null) 세그멘테이션 오류라고합니다.세분화 오류가 발생하는 이유는 무엇입니까?

주소 구조체에 포함 된 포인터와 함께 동적으로 할당 한 구조체 (주소) 배열이 있습니다. 내가 문자열을 구문 분석하고 초기 공백 다음에 오는 하위 문자열을 가져야하므로 거리 이름으로 주소를 정렬하려고합니다. 예를 들어, '123 Anywhere St.'의 경우 'Anywhere St.'부분 문자열을 가져와야합니다. 정렬을 위해 해당 문자열을 비교합니다.

내가이 문제를 일으킬 수있는 잘못은 무엇입니까?

/*Prints the array sorted from a-z by street name*/ 
void printStreetSortedArray(Address * array, int total) 
{ 
    int i; 
    int j, k, z; 
    char temp1[256], *sub_string1; 
    char temp2[256], *sub_string2; 
    Address tmpAdd; 

    for(i=0; i<total-1; i++) 
    { 
     for(j=i+1; j<total; j++) 
     { 
      //Get the two substrings (street names) for comparison 
      strcpy(temp1, array[i].street); 
      z = 0; 
      while(temp1[z] != ' ') 
      { 
       z++; 
      } 
      sub_string1 = temp1+z+1; 

      strcpy(temp2, array[j].street); 
      z = 0; 
      while(temp2[z] != ' ') 
      { 
       z++; 
      } 
      sub_string2 = temp2+z+1; 

      //Compare street names and swap addresses 
      if(strcasecmp(sub_string2, sub_string1) < 0) 
      { 
       tmpAdd = array[i]; 
       array[i] = array[j]; 
       array[j] = tmpAdd; 
      } 
     } 
    } 

    //If I print using this format, it will work correctly 
    /*printAddress(array[0]); 
    printf("\n"); 
    printAddress(array[1]); 
    printf("\n"); 
    printAddress(array[2]); 
    printf("\n");*/ 

    //Trying to print with this format causes a segmentation fault 
    for(k=0; k<total; k++); 
    { 
     printAddress(array[k]); 
    } 
} 

for 루프를 사용하여 인쇄 할 때 다른 모든 정렬 방법이 잘 작동합니다.

/*Allocate memory for array of Addresses*/ 
    myAdd = (Address*)malloc((*total)*sizeof(Address)); 

과 :

fgets(line, sizeof(line), fin); 
line_length = strlen(line); 
line[line_length-1] = '\0'; line_length--; 
myAdd[i].street = malloc(line_length+1); 
strcpy(myAdd[i].street, line); 

이 사람이 올바른 방향으로 날 조종 할 수 있습니다 여기에 내 채우기 배열 방법의 배열 및 주소 표시 줄을 할당하는 방법이다? 그것은 배열 포인터 나 뭔가를 잃어버린 것과 같습니다. 도와 주셔서 감사합니다.

+0

.... 그리고 그것은 단지 거짓말입니다. 나는 ';'을 가졌다. 내 for 루프 선언 다음에. 누구나 지금이 질문을 무시할 수 있습니다. –

답변

1

나는 ';' for 루프 선언 다음에. 너는 얼마나 멍청한 느낌인지 모르겠다.

//Trying to print with this format causes a segmentation fault 
for(k=0; k<total; k++); //<-- ';' 
{ 
    printAddress(array[k]); 
} 

이해야합니다 그것을보고의

for(k=0; k<total; k++)// <-- no ';' 
{ 
    printAddress(array[k]); 
} 

5 시간 후, 나는 마침내 그것을 보았다.

관련 문제