2012-09-30 3 views
0

방금 ​​연결된 구조 목록에 정보가 저장된 코스의 GPA를 계산하는 실험실에서 시작되었습니다. 지금은 모든 코스 정보를 제대로 인쇄하여 링크 목록에 제대로 초기화되었는지 확인하려고합니다.구조체 링크 목록 분할 오류

나는 세그먼트 오류가 계속 발생하기 때문에 문제가 발생합니다. 세그멘테이션 오류의 의미를 이해하지만 실수를 저지르고있는 부분을 알지 못합니다. 어떤 도움을 주시면 감사하겠습니다. 첫 번째 노드 (head == NULL)를 삽입 할 때

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

#define MAX_CLASSES 20 


/* Function Prototypes */ 
struct course * initcourse(int, char *, char *, float, char *, char *); 
void add(struct course *); 

/* Definition of a data node holding course information */ 
    struct course { 
    int term; 
    char name[15]; 
    char abbrev[20]; 
    float hours; 
    char grade [4]; 
    char type[12]; 
    struct course *next; 
    }; 


/* head points to first node in list, end points to last node in list */ 
/* initializes both to NULL, no nodes yet */ 
struct course *head = (struct course *) NULL; 
struct course *end = (struct course *) NULL; 


/* Initializes a node, allocates memory for the node, and returns  */ 
/* a pointer to the new node. Must pass correct parameters.   */ 
struct course * initcourse(int term, char *name, char *abbrev, float hours, char *grade, char *type) 
{ 
    struct course *ptr; 
    ptr = (struct course *) calloc(1, sizeof(struct course)); 
    if(ptr == NULL) 

    return (struct course *) NULL; 

    else 
    { 
     ptr->term = term; 
     strcpy(ptr->name, name); 
     strcpy(ptr->abbrev, abbrev); 
     ptr->hours = hours; 
     strcpy(ptr->grade, grade); 
     strcpy(ptr->type, type); 
     return ptr; 
    } 
} 


/* This adds a node to the end of the list. You must allocate a node and */ 
/* then pass its address to this function        */ 
void add(struct course *new) 
{ 
    if (head == NULL) 
    { 
     head = new; 
    } 
    else 
    { 
     end->next = new; 
     end = new; 
    } 
} 

/* Prints all information in a node */ 
void printnode(struct course *ptr) 
{ 
    printf("Term ->%d\n", ptr->term); 
    printf("Name ->%s\n", ptr->name); 
    printf("Abbreviation ->%s\n", ptr->abbrev); 
    printf("Hours ->%f\n", ptr->hours); 
    printf("Grade ->%s\n", ptr->grade); 
    printf("Type ->%s\n", ptr->type); 
} 




/* Prints List of Nodes */ 
void printlist(struct course *ptr) 
{ 
    while(ptr != NULL) 
    { 
     printnode(ptr); 
     ptr = ptr->next; 
    } 
} 

/* Calculates GPA */ 
/* float gpa (struct course *ptr) */ 
/* { */ 
/* float totalhours; */ 
/* float gpa; */ 
/* float gradepoints; */ 

/* while (ptr != NULL) */ 
/*  { */ 
/*  totalhours += (ptr->hours); */ 
/*  gradepoints = (ptr->hours * ptr->grade); */ 
/*  } */ 
/* gpa = (gradepoints /ptr->hours); */ 
/* } */ 



int main() 
{ 

    int term; 
    char name[15]; 
    char abbrev[20]; 
    float hours; 
    char grade[4]; 
    char type[12]; 
    float gpa; 
    struct course *ptr; 

    struct course course1, course2, course3; 

    course1.term = 1234; 
    strcpy(course1.name,"cse1234"); 
    strcpy(course1.abbrev,"systems"); 
    course1.hours = 4; 
    strcpy(course1.grade,"A"); 
    strcpy(course1.type,"GEC"); 


    ptr = initcourse(course1.term, course1.name, course1.abbrev, course1.hours, course1.grade, course1.type); 

    struct course *head, *ptr2; 
    head = ptr; 
    // ptr2 = ptr; 

    add(ptr); 

    course2.term = 4332; 
    strcpy(course2.name,"cse4332"); 
    strcpy(course2.abbrev,"Database"); 
    course2.hours = 4; 
    strcpy(course2.grade,"B"); 
    strcpy(course2.type,"Technical"); 

    ptr2 = initcourse(course2.term, course2.name, course2.abbrev, course2.hours, course2.grade, course2.type); 

    add(ptr2); 

    printlist(head); 



} 
+0

seg fault = ** 디버거를 사용하십시오! ** –

답변

2
void add(struct course *new) 
{ 
    if (head == NULL) 
    { 
     head = new; 
    } 
    else 
    { 
     end->next = new; 
     end = new; 
    } 
} 

당신은 더 노드를 추가 할 때, 그렇지 않으면 당신은 널 포인터를 역 참조하고, newend를 설정해야합니다.

그리고 initcourse, 당신은이 모든 비트 - 0이 널 포인터 표현 인 표준이 보장되지 않기 때문에 (이 가능성이 매우하지만 보장은 없다, NULLnext 멤버를 설정한다고). 또한

,

struct course *head, *ptr2; 
head = ptr; 

은 글로벌 한 그림자 새로운 지역 변수 head를 선언하고 대신 (그것이 잘못된 일이 비록) head에 직접 할당, 당신은 add(ptr);를 호출해야합니다.

+0

감사합니다. 문제가 해결되었습니다. 또 다른 빠른 질문이 있습니다. (새 게시물을 작성해야할지 모르겠 음) 각 문자 등급을 적절한 등급 점수로 정의하려고합니다. Where A = 4.0 B = 3.0 #define 문을 사용하면이 작업을 수행 할 수 있지만 +/-을 정의 할 수는 없습니다. 예를 들어 "A-"는 = 3.7이어야합니다. 이 편지 등급을 모두 정의 할 수있는 적절한 방법이 있습니까? "#define"지시어가이 작업을 처리하는 적절한 방법입니까? 어떤 도움을 주셔서 감사합니다. 그리고 이것이 이것이 잘못된 곳이라면 사과드립니다. -Matt –

+0

'+'또는 '-'가 포함 된 이름을 '정의'할 수 없으므로 다른 경로를 사용해야합니다. 나는 최선의 방법이 무엇인지 모르겠다. 당신은 A에서 F까지, 가능한 + 또는 -로 각각 점수를 매긴다. 그러면 첫 번째'char'의'switch '는 두 번째를 기반으로 한 수정이 방법 일 수 있습니다. –

0

next 포인터를 초기화하지 마십시오. 마지막 요소에 불량 포인터가 포함되어 일부 가비지를 가리 킵니다.

end도 초기화하지 않습니다.

head = ptr; 
add(ptr); 

다른 문제가있어 :

(안 충돌 관련) 또 다른 문제는이 코드가 중복 항목을 만들 것입니다. 디버거를 얻고 무슨 일이 일어나는지보아야합니다.