为什么我的冒泡排序会出现分段错误?

问题描述 投票:0回答:1

我的代码中的冒泡排序有效,但是当程序去打印新排序的列表时,我会遇到分段错误。

我打印出交换序列,它表明它是正确的。排序发生后程序分段出错,并按顺序打印列表。我不确定这里到底出了什么问题。

#include <stdio.h>
#include <stdlib.h>

typedef struct node_t {
  int num;
  struct node_t *next;
  struct node_t *prev;
} node_t;

void add_node (struct node_t **head, int num) {
  struct node_t *new = (struct node_t*)malloc(sizeof(struct node_t));
  struct node_t *last = *head;
  new->num = num;
  new->next = NULL;

  if (*head == NULL) {
    new->prev = NULL;
    *head = new;
    return;
  } else {
    while (last->next != NULL) {
      last = last->next;
    }
    last->next = new;
    new->prev = last;
  }
  return;
}

void swap_num(struct node_t **first, struct node_t **second) {
    struct node_t *temp;
    printf("%d %d\n", (*first)->num, (*second)->num);
    temp->num = (*first)->num;
    (*first)->num = (*second)->num;
    (*second)->num = temp->num;
}

void sort(struct node_t **head) {
  int swapped;
  struct node_t *temp;

  if (*head == NULL){
    printf("list is empty...\n");
    return;
  }
  do {
    swapped = 0;
    temp = *head;

    while (temp->next != NULL) {
      if (temp->num > temp->next->num) {
        swap_num(&temp, &(temp->next));
        swapped = 1;
      }
      temp = temp->next;
    }

  } while (swapped);
}

void print_list (struct node_t **head) {
  struct node_t *temp;

  if (*head != NULL) {
    temp = *head;
    while (temp != NULL) {
      printf("%d ", temp->num);
      temp = temp->next;
    }
    printf("\n");
  }
}

int main (void) {
  struct node_t *head = NULL;
  int new_num, x, y, kill;

  while (new_num != 0) {
    scanf("%d", &new_num);
    if (new_num != 0) {
      add_node(&head, new_num);
      print_list(&head);
    }
  }

  print_list(&head);
  sort(&head);
  printf("------------------\n");
  print_list(&head);
  return 0;

}
c bubble-sort
1个回答
1
投票

这似乎是你的问题:

..\main.c: In function 'swap_num':
..\main.c:40:15: error: 'temp' is used uninitialized in this function [-Werror=uninitialized]
     temp->num = (*first)->num;
     ~~~~~~~~~~^~~~~~~~~~~~~~~

我使用编译选项,如-Wall-Wextra-Werror得到了这个。如果我解决了这个问题,你的代码就不会崩溃。为了解决这个问题,我只使用int临时值而不是struct node_t*。这是我修改后的swap_num()函数:

void swap_num(struct node_t **first, struct node_t **second)
{
    int temp;
    printf("%d %d\n", (*first)->num, (*second)->num);
    temp = (*first)->num;
    (*first)->num = (*second)->num;
    (*second)->num = temp;
}
© www.soinside.com 2019 - 2024. All rights reserved.