2012-07-17 121 views
-1

我將乘以用戶必須輸入的兩個多項式。c/C++鏈接列表

在第一步

(正從用戶信息)我得到這個錯誤:

Unhandled exception at 0x00a315cb in linked polinomials.exe: 
    0xC0000005: Access violation writing location 0x00000000. 

我之後,我想進入多項式的其他元素此錯誤。

struct polynomial{ 

    float coef ; 
    int exp ; 
    polynomial *next ; 
} *first, *second ,*result; 
first = new(polynomial); 
    //init first 
first ->coef = 0; 
first->exp = 0 ; 
first->next = 0; 
while(ch != 'n') 
{ 
    cin >> temp_c ; 
    cin >> temp_e ; 
    first->coef = temp_c; 
    first->exp = temp_e; 
    cout << "Do you want to enter another ? (y or n) :" << endl; 
    ch = getch(); 
    first = first->next; 
} 
+0

因爲這是C++而不是C,爲什麼不使用std ::清單? – 2012-07-17 08:15:17

+1

沒有C/C++這樣的東西。不要在C++中使用指針,至少在所有方面都是如此。 – 2012-07-17 08:16:54

+1

當你的程序崩潰時,你應該做的第一件事就是在調試器中運行它。它會幫助你找到崩潰的位置,並且讓你檢查變量以查明原因可能是什麼。 – 2012-07-17 08:28:07

回答

0

在第一次迭代:

first = first->next; 

分配firstNULL,因爲那是什麼first->next最初。您需要在分配前爲其分配空間。

first->next = new polynomial; 
first = first->next; 

另外,你確定要丟失指向第一個節點的指針嗎?

+0

@hadirasuli使用輔助節點,而不是'first'。 – 2012-07-17 17:48:20

0

您沒有爲整個列表分配內存。 你需要寫這樣的事:
first->next = new polynomial();
first = first->next;

否則,你想在NULL地址讀取內存。

0

相反,你應該做的:

second = new(polynomial); 
first->next=second; 
first=second; 
+0

感謝它的工作! – Stuart 2012-07-17 08:20:12

0
first = first->next; 

此操作之前,你必須爲

first->next = new polynomial(); 

和一個新的鏈接,例如分配內存後,纔可以寫

first = first->next;