2016-01-23 142 views
-3

我想创建一个链表,但每当我尝试将数据分配给结构中的数据字段时,我会得到分段错误..Plz帮助?通过指针赋值给结构域时,分段错误?

struct Node 
{ 
    int data; 
    Node* next; 
}; 


int main() 
{ 
    ios_base::sync_with_stdio(false); 
    Node* start=NULL; 
    Node* prev=NULL; 
    int N,Q,L,M,R,x; 
    cin>>N>>Q; 
    cin >> x; 
    start->data = x; // The Line where i get error 
    start->next=NULL; 
    prev = start; 
    return 0; 
} 
+2

您试图从NULL指针访问内存位置,因为'Node * start = NULL;' –

+1

您需要[好书](http://stackoverflow.com/questions/388242/the-definitive-c -book引导和列表)。你绝对不需要'ios_base :: sync_with_stdio(false);'。 – molbdnilo

+0

这不是整个代码,它只是一个部分... ios_base :: sync_with_stdio(false);这是上下文所要求的。无论如何,我试图声明这些指针后声明的结构没有初始化为空,同样的错误仍然 –

回答

0

您正在node类型的指针,但没有给它分配内存。如果没有分配内存,您尝试访问start->data。 为此,您得到分段错误

  • 首先分配内存启动和prev。
  • 然后访问它。

例如:

Node* start=NULL; 
start= new Node; //allocate memory where your start pointer will point 
start->data = x; 

编辑

请检查使用new运营商。我不确定哪一个是正确的start = new Node;start = new Node();

您也可以使用malloc分配内存;