2012-09-30 5 views
0

아래 구조체로 연결된 학생 목록을 만들려고합니다.학생 구조의 링크 된 목록 구현

struct student 
{ 
    int student_ID; 
    char *student_name; 
    struct course *courses_enrolled; 
    Student *child; 
}; 

//Insert student to the list with a given student pointer and the starting point 
Student *insert_student(Student *child, Student *root) 
{ 
    Student *temp = (Student*)malloc(sizeof(Student)); 
    //if there isn't a starting point, declare this as the start point 
    if(root->student_name == NULL) 
    { 
     root->student_ID = child->student_ID; 
     root->student_name = strdup(child->student_name;); 
     root->child = NULL; 
    } 
    //if this student's name is before current node, replace node. 
    else if(strcmp(child->student_name, root->student_name) < 0) 
    { 
     temp = root; 
     root = child; 
     child->child = temp; 
    } 
    //if this student's name is after current node, keep doing insert recursion 
    else if(strcmp(child->student_name, root->student_name) > 0) 
    { 
     insert_student(child, root->child); 
    } 

    return root; 
} 

첫 번째 루트 삽입은 항상 잘 작동 것이다 그러나 나는 2를 추가하려고 할 때, 프로그램은 SEG insert_student하는 2 호출 후에 잘못됩니다. 내가 그 의심 비교

if(root->student_name == NULL) 

에서 실패 나 루트 (루트 레벨> 아이)의 자식 노드에 접근 함께 할 수있는 뭔가가하지만 난 정말로 확실하지 않다.

p/s : 내가 할당을 해제하지 않는다는 것을 알고 있습니다. 이것은 다른 라이브러리를 사용해야하는 임시 작업 일뿐입니다.

업데이트 : 초과 코드가 제거되었습니다.

답변

1

이 함수가 어떻게 호출되는지에 대한 정확한 문제를 찾기가 약간 어렵습니다. 확인하고 싶은 몇 가지 사항이있는 것으로 보입니다. 두 번째 지점이 발생하지 않도록

난 당신이 함수에 전달 된 childroot은 참으로 모든 NULL로 설정 루트 필드와 그 학생의 이름으로 할당된다고 가정하고하는 것은 순서에 있습니다. 그런 다음 첫 번째 삽입이 작동합니다.

하지만 두 번째 삽입 작업을 수행 할 때. 첫 번째 if 절에 NULL으로 설정 한 root->child을 전달 중입니다. 이로 인해 NULL에서 참조를 취소 할 수 없으므로 이후 strcmp이 실패합니다 (예 : NULL->student_name에서 오류가 발생 함).

0

insert_student를 재귀 적으로 호출 할 때 root으로 전달하는 값이 null이 아닌지 확인해야합니다. 마지막에 삽입하는 것과 같이 null 인 경우 다른 사례가 필요할 수 있습니다.

내가 알아챈 한 가지는 할당 된 값인 temp을 결코 사용하지 않는다는 것입니다. temp을 사용하기 전에는 항상 사용하지 않거나 버려집니다. 나는 이것이 당신이 원하는 것이 아니라고 생각하고 있습니다. 일반적으로 단어 next 대신 newStudent 같은 구조체 뭔가에 child 또는 대신 매개 변수 아이의 단지 student으로 사용될 것 또한

.

+0

네, 그 부분에서 실패하지 않는 것이 맞습니다. 다시 확인해 보았습니다. 실제로 비교에 실패했다고 생각합니다 (이를 반영하기 위해 내 게시물을 편집했습니다). 나는 또한 임시 할당을 제거했다. 그것은 내가 제거한 다른 것을위한 것이라고 생각했다. – rlhh

0
if(root->student_name == NULL) 
{ 
    printf("Always here?\n"); 
    root->student_ID = child->student_ID; 
    root->student_name = strdup(child->student_name); 
    temp->student_ID = 0; 
    temp->student_name = NULL; 
    root->child = temp; 
} 

실제로 액세스하려면 먼저 자식 노드의 변수를 NULL로 선언해야한다는 것을 알았습니다.