2015-11-22 45 views
0

我正在嘗試編寫一個程序,它可以在表達式中找到所有")"並將它們放入鏈接列表中,並始終在列表的開頭添加。問題是,當我嘗試將新元素放入列表中時,程序停止工作。無法將元素插入到鏈接列表

與樣本用戶輸入865)987

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

typedef struct element { 
    char data; 
    struct element *next; 
} ELEMENT; 


int main(void) 
{ 
    ELEMENT *first = NULL; 
    ELEMENT *new_a; 

    char input[30]; 
    int x=0; 

    printf("Input expression: "); 
    scanf("%s", &input); 

    while(input[x]!='\0'){ 
     if (input[x]==')'){ 
      printf("%c", input[x]);  //This works just fine. 
      new_a->data = input[x];  //Here, the program stops working. 
      new_a->next = first; 
      first = new_a; 
     } 
     x++; 
    } 
} 

我在做什麼錯?

回答

4
new_a->data 

相當於

(*new_a).data 

正如你所看到的,new_a被試圖取消引用。問題在於new_a未初始化的,因此任何隨後的解除引用的嘗試都是未定義的行爲(以形狀例如分段錯誤)。

爲了解決這個問題,你需要爲new_a分配內存:

  1. 在棧上分配空間。這隻有在main中專門使用鏈表時纔有效,因爲局部變量的範圍爲only embraces the beginning and end of a function
    像這樣做:

    ELEMENT new_a; 
    
    ... 
    
    new_a.data = input[x]; 
    new_a.next = first; 
    first = &new_a; 
    
  2. 使用malloc這通常用於鏈表和適用於現有的,直到你的程序的終止很鏈表,因爲它的範圍無關:

    ELEMENT* new_a = malloc(sizeof(ELEMENT)); 
    

    不要忘了free算賬!


注:

+0

非常感謝你,現在它似乎是工作!只是一個小問題:「first = &new_a;」,「不兼容指針類型的賦值」有一條新警告。你碰巧知道這是爲什麼? – DerekT

+0

@DerekT **或者**在'ELEMENT new_a;'**(注意缺少星號!)**並使用'first = &new_a; ** **或**在堆棧上分配' malloc'並使用'first = new_a;'。或者是別的什麼?如果您的問題未解決,請*添加錯誤消息*。 – Downvoter

0

您需要爲new_a分配內存:

new_a = malloc(sizeof(ELEMENT)); 
0

以前作爲回答,正確的代碼是:

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

typedef struct element { 
    char data; 
    struct element *next; 
} ELEMENT; 

int main(void) 
{ 
    ELEMENT *first = NULL; 
    char input[30]; 
    int x=0; 

    printf("Input expression: "); 
    scanf("%s", &input); 

    while(input[x]!='\0'){ 
     if (input[x]==')'){ 
      ELEMENT *new_a = (ELEMENT*)malloc(sizeof(ELEMENT)); 
      printf("%c", input[x]); 
      new_a->data = input[x]; 
      new_a->next = first; 
      first = new_a; 
     } 
     x++; 
    } 
} 
+0

scanf(「%s」,&輸入);應該是scanf(「%s」,輸入);不需要轉換malloc返回值。併爲一致性應該有返回0主 – amdixon

+0

@amdixon因爲,你是對的!但我只是複製athor代碼並修復添加節點到列表的錯誤。不過,我認爲malloc的返回值更好,那麼不要這樣做。 –

+0

@AntonTodua,實際上,它不是更好http://stackoverflow.com/a/605858/817643 – StoryTeller