2013-04-21 59 views
0

我想構建一個程序,它接受用戶輸入,然後反轉輸入。輸出顯示原始字符串和反轉字符串。程序編譯,但給了我下面的錯誤「0ÿÿÿ;原始鏈接列表分段錯誤(核心轉儲)」雙向鏈接的用戶輸入

這裏是我的代碼:

struct node 
{ 
int info; 
struct node *next; 
struct node *prev; 
}node; 
void reverse(struct node **head_1) 
{ 
struct node *temp = NULL; 
struct node *current = *head_1; 
while (current != NULL) 
    { 
     temp = current->prev; 
     current->prev = current->next; 
     current->next = temp; 
     current = current->prev; 
    }  
     if(temp != NULL) 
     *head_1 = temp->prev; 
    }  
void push(struct node** head_1, int new_data) 
{ 
    struct node* new_node = 
    (struct node*) malloc(sizeof(struct node)); 

    new_node->info = new_data; 
    new_node->prev = NULL; 
    new_node->next = (*head_1); 
    if((*head_1) != NULL) 
     (*head_1)->prev = new_node ; 
     (*head_1) = new_node; 
} 
void printList(struct node *node) 
{ 
while(node!=NULL) 
    { 
    printf("%s ", node->info); 
    node = node->next; 
    } 
     } 

int main() 
{ 
struct node* head = NULL; 
char str[300], ch; 
int i; 
printf("enter "); 
    while((ch=getchar())!='\n'); 
{ 
str[i++]=ch; 
str[i]='0'; 
i=0; 
} 
    while (str[i]!='\0') 
{ 
putchar(str[i++]); 
push(&head, ch); 
} 
    printf("\n Original "); 
    printList(head); 
    reverse(&head); 
    printf("\n Reversed "); 
    printList(head);   

    getchar(); 
    } 

回答

0

您正在使用未初始化的變量i訪問str

int i;//Unitialized variable 
printf("enter "); 
    while((ch=getchar())!='\n'); 
{ 
str[i++]=ch;//This will acess memory at address str+random value from i 

變化int i;to int i = 0;

而且printf("%s ", node->info);不正確,因爲node->info是整數,而不是字符串。應該是這樣的printf("%d ", node->info);

我有點額外的問題,通過我懷疑它是最終的。

while((ch=getchar())!='\n');//why ;? this will lead to all chars to be skipped and only \n will be passed to the loop body 
{ 
str[i++]=ch; 
str[i]='0';//it should be '\0' instead of '0', and there is no sense to set it on each iteration 
i=0;//This will reset i on each iteration overwriting previous char 
} 
+0

嗨!感謝您的評論。我提出了你所提到的改變。我不再收到同樣的錯誤消息,但現在我得到了 0ÿÿÿ; 原始101010101010 反轉101010101010^ 與任何輸入 – 2013-04-22 00:38:52