ошибка сегментации при добавлении станции, уже присутствующей в списке с помощью программирования c - PullRequest
0 голосов
/ 15 октября 2018

Я пытаюсь добавить список станций, в котором, если имя станции уже присутствует в едином связанном списке, тогда название станции добавлять не нужно.Но когда я выполняю сравнение строк в функции findtation, я получаю ошибку сегментации.Я давно отлаживаю.Я не мог найти, где я иду не так.Было бы очень полезно, если бы я узнал свою ошибку.Заранее спасибо.

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

    struct station
    {
        char station[100];
        struct station *next;
    }destinations;


    struct station *findStation(struct station *stations,char *station_name);
    void addStation(struct station **stations,char *station_name);
    //void addDestination(struct station *stations, char *station_name);
    void printStations(struct station *stations);
    //void removeStation(struct station **stations, char *station_name);
    int findShortestPath(struct station *stations, struct station *a, struct station *b);

    int main()
    {
        struct station *source = NULL;
        char *station_name;
        char c;
        bool quit=false;
        while(!quit)
        {
            scanf("%c",&c);
            switch(c)
            {
                case 'a':
                {
                    scanf(" %s", station_name);
                    addStation(&source,station_name);
                    break;
                }
                case 'd':
                {
                    scanf(" %s",station_name);
                    //addDestination(&destinations,station_name);
                    break;
                }
                case 'p':
                {
                    printStations(source);
                    break;

                }
                case 'q':
                {
                    quit=true;
                    break;
                }
                default:
                    break;
            }
        }
        return 0;
    }


    struct station *findStation(struct station *stations,char *station_name)
    {
        //returns a pointer to the station with the name station name in the list stations
            struct station *find=NULL;
            printf("h1");
            //printf("%s",station_name);
            //printStations(stations);
            while((stations!=NULL))
            {
                if(strcmp(stations->station,station_name)!=0)
                {
                    printf("%s\n", stations->station);
                    printf("%s\n", station_name);
                    stations=stations->next;
                    find=stations;
                    //printf("hello");
                }
                else
                {
                  find=NULL; 
                 // printf("bye");
                  return ;
                }
            }
            //printStations(find);
            return find;
    }

    void addStation(struct station **stations,char *station_name)
    {
        struct station *find;
        struct station *temp;
        temp= (struct station *)malloc(sizeof(struct station ));
        //adds a new station with the name station name to the front of the list stations
        if(*stations== NULL)
        {
            strcpy(temp->station,station_name);
            temp->next=NULL;
            (*stations)=temp;

        }
        else
        {
            //printf("hi");
            find= findStation(*stations,station_name);
            printStations(find);
            if(find !=NULL)
            {
                printf("Station station_name already exists.");
                    exit (0);
            }
            else
            {
            strcpy(temp->station,station_name);
            temp->next=NULL;
            temp->next=(*stations);
            (*stations)=temp;
            }

        }

    }

        enter code here

Ответы [ 2 ]

0 голосов
/ 15 октября 2018

Попробуйте это:

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

struct station
{
    char station[20];
    struct station *next;
}destinations;


struct station *findStation(struct station *stations,char *station_name);
void addStation(struct station **stations,char *station_name);
//void addDestination(struct station *stations, char *station_name);
// void printStations(struct station *stations);
//void removeStation(struct station **stations, char *station_name);
int findShortestPath(struct station *stations, struct station *a, struct station *b);

int main()
{
    struct station *source = NULL;
    char station_name[20];
    char c;
    bool quit=false;
    while(!quit)
    {
        scanf("%c",&c);
        switch(c)
        {
            case 'a':
            {
                scanf(" %s", station_name);
                addStation(&source,station_name);
                break;
            }
            case 'd':
            {
                scanf(" %s",station_name);
                //addDestination(&destinations,station_name);
                break;
            }
            case 'p':
            {
                // printStations(source);
                break;

            }
            case 'q':
            {
                quit=true;
                break;
            }
            default:
                break;
        }
    }
    return 0;
}


struct station *findStation(struct station *stations,char *station_name)
{
    //returns a pointer to the station with the name station name in the list stations
        struct station *find=NULL;
        printf("h1");
        //printf("%s",station_name);
        //printStations(stations);
        while((stations!=NULL))
        {
            if(strcmp(stations->station,station_name)!=0)
            {
                printf("%s\n", stations->station);
                printf("%s\n", station_name);
                stations=stations->next;
                find=stations;
                printf("Not found any match \n");
            }
            else
            {
              find=NULL; 
             // printf("bye");
             printf("Found any match \n");
              return NULL;
            }
        }
        //printStations(find);
        return find;
}

void addStation(struct station **stations,char *station_name)
{
    struct station *find;
    struct station *temp;
    temp= (struct station *)malloc(sizeof(struct station ));
    //adds a new station with the name station name to the front of the list stations
    if(*stations== NULL)
    {
        strcpy(temp->station,station_name);
        temp->next=NULL;
        (*stations)=temp;
    }
    else
    {
        //printf("hi");
        find= findStation(*stations,station_name);
        // printStations(find);
        if(find == NULL)
        {
            printf("Station station_name already exists.");
            exit (0);
        }
        else
        {
            strcpy(temp->station,station_name);
            temp->next=NULL;
            temp->next=(*stations);
            (*stations)=temp;
        }

    }

}
0 голосов
/ 15 октября 2018

Здесь есть как минимум 2 проблемы:

Первая проблема

Функция findStation имеет несколько проблем, это исправленная версия:

struct station *findStation(struct station *stations, char *station_name)
{
  //returns a pointer to the station with the name station name in the list stations
  printf("h1");

  while ((stations != NULL))
  {
    if (strcmp(stations->station, station_name) == 0) //<< use == instead of !=
                                                      // read the documentation of `strcmp`
    {
      printf("%s\n", stations->station);
      printf("%s\n", station_name);
      return stations;                                 //<< station found, return it
    }
  }

  return NULL;                                         //<< no station found => return NULL
}

Не усложняйте, чем нужно.

Вторая задача

char *station_name; должна быть char station_name[100];.

В строке scanf(" %s", station_name), station_name должен быть указатель на буфер, куда должна идти ваша строка.char *station_name; объявляет указатель, но он нигде не указывает, тогда как char station_name[100]; объявляет массив из 100 символов, и в этом случае station_name является допустимым указателем на ваш буфер.

Прочитайте главу, посвященную указателям итот, который имеет дело со строками в вашей книге C texgt.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...