2012-10-23 52 views
0

我的代碼如下:它要求用戶輸入星球名稱,距離和描述。然後它會打印出用戶輸入的任何內容。我的代碼中的鏈表和分段錯誤錯誤

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

/* planet type */ 
typedef struct{ 
    char name[128]; 
    double dist; 
    char description[1024]; 
} planet_t; 

/* my planet_node */ 
typedef struct planet_node { 
    char name[128]; 
    double dist; 
    char description[1024]; 
    struct planet_node *next; 
} planet_node; 

/* the print function, not sure if its correct */ 
void print_planet_list(planet_node *ptr){ 
    while(ptr != NULL){ 
    printf("%s %lf %s\n", ptr->name, ptr->dist, ptr->description); 
    ptr=ptr->next; 
    } 
    printf("\n"); 
} 

int main(){ 
    char buf[64]; 
    planet_node *head = NULL; 
    int quit = 0; 

    do { 
    printf("Enter planet name (q quits): "); 
    scanf("%s",buf); 
    if((strcmp(buf,"q")==0)){ 
     quit = 1; 
    } 
    else{ 
     planet_node *new = malloc(sizeof(planet_node));  /* New node */ 
     strcpy((*new).name, buf);   /* Copy name */ 
     printf("Enter distance and description: "); 
     scanf(" %lf ", new->dist); /* Read a new distance into pluto's */ 
     gets(new->description);  /* Read a new description */ 
     new->next = head;  /* Link new node to head */ 
     head=new;  /* Set the head to the new node */ 
    } 
    } while(!quit); 

    printf("Final list of planets:\n"); 
    print_planet_list(head); 


    while(head != NULL){ 
    planet_node *remove = head; 
    head = (*head).next; 
    free(remove); 
    } 
} 

這裏我提出的意見是地方哪裏我不知道,如果它是正確的,代碼是否符合,但給了我一個分割錯誤。 有幫助嗎?謝謝。

+1

避免你編譯所有警告和調試信息的代碼(在Linux上使用'GCC -Wall -g')?然後改進代碼,直到沒有發出警告。最後使用調試器(Linux上的'gdb')和泄漏檢測器(Linux上的'valgrind')進行調試。 –

+0

我在VC中沒有收到錯誤(編譯或運行)。雖然我確實改變了「新」 - 這是C++中的一個關鍵詞。 –

+0

@MarkStevens但不在'C'。所以如果你使用.c擴展名,它編譯得很好。 –

回答

3

scanf(" %lf ", new->dist);

這是你的錯誤。 它應該是:

scanf(" %lf ", &(new->dist));

還額外「」使它接受額外的字符。這可以用

scanf("%lf", &(new->dist));

+1

請注意,這個錯誤會被'gcc -Wall'發出警告。 –

+0

@BasileStarynkevitch不幸的是我沒有gcc,但是我在一讀時就發現了它。 :P。編譯器在我腦子裏是比較慢但更準確的(我認爲):D –

+0

僅供參考,實際警告是「test.c:44:7:警告:格式'%lf'需要'double *'類型的參數,但參數2有'double'類型[-Wformat] test.c:60:1:warning:控制達到非void函數結束[-Wreturn-type]「 – harpun