Вставка и сортировка связанного списка для программирования на C

Здравствуйте, я новичок в c, поэтому у меня было несколько проблем с моим кодом. Мой код должен отображать меню, которое отображается, если вы хотите добавить, найти, удалить или распечатать все. Это работает, однако, моя часть вставки не. Когда я выбираю добавить и начинаю вводить информацию, которую я хочу, программа вылетает?

вот мой код

#include <stdio.h>   
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#pragma warning(disable: 4996)
//#define max 100

typedef enum { diploma, bachelor, master, doctor } education;

struct person {  // a node to hold personal details
char name[30];
char email[30];
int phone;
education degree;
struct person* next;
} *head;


void branching(char c);
int insertion();
struct person *search(char *sname);
void deletion(char *sname);
void print_all();

char *x;

//Main Method
 int main() {  // print a menu for selection
 char ch;

do {
    printf("Enter your selection\n");
    printf("\ti: insert a new entry\n");
    printf("\td: delete an entry\n");
    printf("\ts: search an entry\n");
    printf("\tp: print all entries\n");
    printf("\tq: quit \n");

     ch = tolower(getchar());
     branching(ch);
    } while (ch != 113);

      return 0;
    }

  void branching(char c) {    // branch to different tasks
switch (c) {
case 'i':
    insertion();
    break;
case 's':
    printf("Enter an item to search");
    scanf("%s", x);
    search(x);
    break;
case 'd':
    printf("Enter an item to delete");
    scanf("%s", x);
    deletion(x);
    break;
case 'p':
    print_all();
    break;
case 'q':
    break;
default:
    printf("Invalid input\n");
    }
  }

//insert entry
int insertion(){
struct person *p;
p = (struct person*)malloc(sizeof(struct person));

if (p == 0){
    printf("There are no more places to insert.\n"); return -1;
}

printf("Enter name, email, phone, and degree:\n");
scanf("%s", p->name);
scanf("%d", &p->phone);
scanf("%s", p->email);
scanf("%i", p->degree);
p->next = head;
head = p;
return 0;
}

   //search method
   struct person *search(char *sname){
   struct person *p = head, *b = p;
   printf("Please enter the name you wish to search:\n");
    scanf("%c", sname);
    while (p != 0)
    if (strcmp(sname, p->name) == 0){
    printf("Phone: %d\n", p->phone);
    printf("Email: %s\n", p->email);
    printf("Degree: %s\n", p->degree);
    return b;
    }
    else{
        b = p;
        p = p->next;
    }
    printf("The name does not exist.\n");
    return 0;
}
    //delete entry
   void deletion(char *sname){
   struct person *t, *p;
   p = head;
   t = head;
   while (t != NULL){
      if (t->name == sname){
          if (t == head){//case 1
            head = t->next;
            free(t);
            return;
        }
        else{
            p->next = t->next;
            free(t);
            return;
        }
    }
    else{
        p = t;
        t = t->next;
      }
  }
   return;
 }

    //print
  void print_all(){
struct person *p;
p = head;
if (p = NULL){
    printf("No entries found.");
}
else{
    while (p != NULL){
        printf("%s", p->name);
        printf("%d", p->phone);
        printf("%s", p->email);
        printf("%s", p->degree);
        p = p->next;
      }
       printf("\n");
      }
    }

1 ответ

Переменная x необходимо указать на действительную память. Когда вы делаете декларацию: char * x;
Указатель неинициализирован и может указывать на любую область памяти компьютера.

Вот почему мы рекомендуем использовать std::string и потоки C++, такие как:

std::string x;
cin >> x;
// or 
std::getline(cin, x);

Помните, что если вы динамически распределяете память для строк в стиле C, вы должны освободить память.

Также вам нужно указать максимальную длину строки для вашего ввода. Вот почему scanf это злая функция. Если вы должны использовать scanfпредпочитаю, чтобы это были другие члены семьи, такие как fscanf(stdin) или используйте спецификатор формата с указанным максимальным размером.

При сравнении строки в стиле C вам нужно будет использовать strcmp, При копировании строки используйте strcpy, Если вы используете std::stringВы можете использовать оператор присваивания и реляционные операторы (более удобный и безопасный).

Другие вопросы по тегам