尝试比较字符串时出现分段错误- C编程

6vl6ewon  于 2022-12-03  发布在  其他
关注(0)|答案(1)|浏览(89)

我正在用链表做一个排序函数。基本上我会输入一个字符串,然后按回车键,它就会在链表中注册。第一个输入的将是链表的头。
当我输入后面的字符串时,我想把它放在更大的字符串之前。如果它比第一个现有的字符串大,我会向下移动到下一个链表,并与第二个现有的字符串进行比较。如果它比第一个现有的字符串小,我会把它放在前面。
因此如果输入为

cat
dog
bird

它将以这样的方式输出

cat
bird
dog

但是,只有前两个可以比较,如果我比较第三个,它会抛出一个分段错误,并结束程序。
似乎不明白为什么我的一个指针-〉字符(ptr-〉character)有一个分段错误。我可以完美地打印出字符,但我不能比较它,因为它给出了一个分段错误。

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX

char userInput[33];
char stopStr[] = "***";
int isInserted = 0;

struct node {
  char characterInput[33];
  // int data;
  struct node *link;
};

void printData(struct node *head) {
  printf("All the entered words in order:");
  if (head == NULL) {
    printf("\nLink List is empty");
  }
  struct node *ptr = NULL;
  ptr = head;
  while (ptr != NULL) {
    printf("\n%s", ptr->characterInput);
    ptr = ptr->link;
  }
}

int main(void) {
  // creating a head
  struct node *head = malloc(sizeof(struct node));

  scanf("%s", &userInput);
  if (strcmp(userInput, stopStr) != 0) {

    for (int i = 0; i < strlen(userInput); i++) {
      userInput[i] = tolower(userInput[i]);
    }
    strcpy(head->characterInput, userInput);
    head->link = NULL;
  } else {
    return 0;
  }

  while (1) {
    struct node *current = malloc(sizeof(struct node));
    struct node *ptr = malloc(sizeof(struct node));
    struct node *ptr2 = NULL;
    ptr = head;
    isInserted = 0;

    scanf("%s", &userInput);
    if (strcmp(userInput, stopStr) == 0) {
      break;
    }

    // convert to lowercase
    for (int i = 0; i < strlen(userInput); i++) {
      userInput[i] = tolower(userInput[i]);
    }
    // insert userinput to node
    strcpy(current->characterInput, userInput);

    //trying to compare between strings in each linked list. If linked list current string is smaller than the string in head, link current to head and make head = current
    if (strcmp(head->characterInput, userInput) > 0) {
      current->link = head;
      head = current;
    } else if (ptr->link == NULL) {
      ptr->link = current;
//else put it at the back of the head if there is no linked list at the back. (if head->link is null)
    }
    else{
      while(isInserted == 0){
        
        ptr2 = ptr;
        
        ptr = ptr->link;
        printf("\n%s",ptr->characterInput); 
//here's the issue, I can print out ptr->character but i cant compare them below, in the if statement against my current user input.
        if(strcmp(ptr->characterInput,userInput)>0){
          
          ptr2->link = current;
          current->link = ptr;
          isInserted = 1;
        }
        
      }
    }
  }

  printData(head);
}
8iwquhpp

8iwquhpp1#

  • 某个程序员说的 *。+你还没有注意到另一种选择,即新元素会进入链表的尾部。你应该在分配currentlink时立即将其置为NULL。并且在while(isInserted == 0)循环中处理ptr-〉link为NULL的情况。

相关问题