2015-11-01 69 views
0

OK,這是在C內存分配到一個鏈表與字符數組節點

struct node 
{ 
    int id; 
    char name[20]; 
    int sem; 

    struct node *link; 
}; 

typedef struct node* Node; 

Node getnode() 
{ 
    Node temp=(Node)(malloc(sizeof(Node))); 
    if(temp==NULL) 
     printf("\n Out of memory"); 

    return temp; 
} 

Node ins_pos(Node first) 
{ 
    Node temp=getnode(); 
    printf("\n Enter id "); 
    scanf("%d",&temp->id); 
    printf("\n Enter name "); 
    scanf("%s",temp->name); 
    printf("\n Enter semester "); 
    scanf("%d",&temp->sem); 

    if(first == NULL) 
    { 
     temp->link=NULL; 
     return temp; 
    } 

    else 
    { 
     int pos,i; 
     printf("\n Enter position: "); 
     scanf("%d",&pos); 

     if(pos == 1) 
     { 
      temp->link=first; 
      return temp; 
     } 

     else 
     { 
      Node prev=NULL,cur=first; 
      for(i=1; i<pos; i++) 
      { 
       if(cur==NULL) 
        break; 

       prev=cur; 
       cur=cur->link; 


      } 

      if(cur==NULL && i < pos) 
       printf("\n Position invalid"); 
      else 
      { 
       prev->link=temp; 
       temp->link=cur; 
      } 

      return first; 
     } 
    } 
} 

Node del(Node first) 
{ 
    if(first==NULL) 
     printf("\n List is Empty "); 
    else 
    { 
     Node temp=first; 
     printf("\n ID: %d was deleted",temp->id); 
     first=first->link; 
     free(temp); 
    } 
    return first; 
} 

void disply(Node first) 
{ 
    if(first==NULL) 
     printf("\n List is empty"); 
    else 
    { 
     Node cur=first; 
     while(cur!=NULL) 
     { 
      printf("\n ID : "); 
      printf("%d",cur->id); 
      printf("\n Name : "); 
      printf("%s",cur->name); 
      printf("\n Semester : "); 
      printf("%d",cur->sem); 
      printf("\n\n\n"); 

      cur=cur->link; 
     } 
    } 
} 
int main() 
{ 
    Node first=NULL; 
    int opt; 

    do 
    { 
      printf("\n QUEUE MENU\n 1.Insert at position \n 2.delete front\n 3.display\n 4.Exit \n\n Enter your choice : "); 
      scanf("%d",&opt); 

      switch(opt) 
      { 
       case 1 :first = ins_pos(first); 
         break; 

       case 2 :first = del(first); 
         break; 

       case 3 :disply(first); 
         break; 

      } 


    }while(opt!=4); 


    return 0; 
} 

當插入一個新的節點簡單單鏈表程序,在malloc的聲明代碼塊崩潰。我怎麼知道?好吧,它在請求「輸入ID」之前崩潰。那麼,我做錯了什麼?

另一點是,它在節點中只有一個整數字段正常工作,這裏的問題可能是字符數組。

回答

1

在此功能Node getnode() -

Node temp=(Node)(malloc(sizeof(Node))); 

利用上述malloc你分配內存等於Node這是類型結構指針,並且是不夠的。因此尺寸,就會得到一個段故障。

取而代之,這樣寫 -

Node temp=malloc(sizeof(*temp));  //also there is no need of cast 

這將分配內存等於類型到temp點即大小等於結構的大小。這是適當的。

+0

我注意到這個答案並不能解釋*爲什麼這解決了這個問題。 – immibis

+0

@immibis我已經添加了解釋。如果您發現任何問題,請隨時指出。謝謝 !! :-) – ameyCU

0

這裏需要使用Node temp=(Node)(malloc(sizeof(*temp)));

+0

抱歉,疏忽。糾正。 – user1969104

1

了一些錯誤。

malloc(sizeof(struct node)); 

否則分配的內存太少。

您是否包含stdlib.h for malloc定義 - 會導致此問題(沒有定義,默認爲int)。