2014-09-19 53 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