2012-07-17 165 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;