2014-09-19 52 views
1

我操縱了我的代碼,以便能夠使用pred_p,但由於此問題而遇到問題。我的代碼停在「pred_p-> next_p = temp_p;」行並給我的消息「主題1:EXC_BAD_ACCESS(代碼= 1,地址= 0x8中)。不知道從哪裏何去何從插入函數中的指針在C中給出錯誤

struct list_node_s { 
    int data; 
    struct list_node_s* next_p; 
}; 

struct list_node_s* Insert(struct list_node_s* head_p, int val); 
void Print(struct list_node_s* head_p); 
char Get_command(void); 
int Get_value(void); 

/*-----------------------------------------------------------------*/ 
int main(void) { 
    char command; 
    int value; 
    struct list_node_s* head_p = NULL; 
    /* start with empty list */ 

    command = Get_command(); 
    while (command != 'q' && command != 'Q') { 
     switch (command) { 
      case 'i': 
      case 'I': 
       value = Get_value(); 
       head_p = Insert(head_p, value); 
       break; 
      case 'p': 
      case 'P': 
       Print(head_p); 
       break; 
      default: 
       printf("There is no %c command\n", command); 
       printf("Please try again\n"); 
     } 
     command = Get_command(); 
    } 

    return 0; 
} /* main */ 


/*-----------------------------------------------------------------*/ 
struct list_node_s* Insert(struct list_node_s* head_p, int val) { 
    struct list_node_s* curr_p = head_p; 
    struct list_node_s* pred_p = NULL; 
    struct list_node_s* temp_p; 

    while (curr_p != NULL) { 
     if (curr_p->data >= val) 
      break; 
     pred_p = curr_p; 
     curr_p = curr_p->next_p; 
    } 

    // Create new node 
    temp_p = malloc(sizeof(struct list_node_s)); 
    temp_p->data = val; 
    temp_p->next_p = curr_p; 
    if (pred_p = NULL) { 
     head_p = temp_p; 
    } 
    else { 
     pred_p->next_p = temp_p; 
    } 

    return head_p; 
} /* Insert */ 
+0

你的代碼是多線程的嗎?這可能是由於併發訪問 – Joel 2014-09-19 21:35:05

+0

您可能會發現[** this alternative **](http://pastebin.com/skPU5Uw7)一段有趣的代碼。 – WhozCraig 2014-09-19 21:42:11

+0

你的代碼有很多問題,下面是一行:if(pred_p = NULL){將pred_p賦值爲NULL,而不是將pred_p與NULL進行比較。 (一個常見的錯誤和字面值應該先寫的原因,所以編譯器會發現問題。 – user3629249 2014-09-22 07:16:31

回答

2
if (pred_p = NULL) 

這應該是

if (pred_p == NULL) 

你技術上重複自己,作爲一個=,簡單地分配給NULL再次pred_p

而且

您需要使用pred_p=malloc(sizeof struct list_node_s)分配內存給pred_p。

以上只會工作過,因爲它是,如果head_p不是NULL,這意味着curr_p不會NULL,進而pred_p但你永遠也不會注意到陷阱。

+0

我應該知道的。謝謝 – 2014-09-19 21:38:19

+0

@TylerS。沒問題:) – 83457 2014-09-19 21:41:52