Strcmp给出了分段错误

时间:2017-10-19 15:46:10

标签: c strcmp fault

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

typedef struct station 
{
    char * name;
    struct station * destinations;
    struct station * next;
} station;
struct station * findStation(station * stations, char * name)
{
    if(stations = NULL)
    {
        printf("ERROR");
        return NULL;
    }
    else
    {
        station * temp;
        for(temp = station; temp->next != NULL; temp = temp->next)
        {
            if(strcmp(temp->name, name) == 0)
            {
                return temp;
            }
        }
    return NULL;  
    }
}
void addStation(station ** stations, char * name)
{
    if(findStation(*stations, name) == NULL)
    {
        station * newstation;
        char name1[32];
        strcpy(name1, name);
        newstation = (station *)malloc(sizeof(station));
        newstation->name = &name1[0];
        if(*stations = NULL)
        {
            *stations = newstation;
        }
        else
        {
            newstation->next = *stations;
            *stations = newstation;
        }
    }
    else
    {
        printf("Station %s already exists.", name);
    }
}
void main(void)
{
    station * stations = NULL;
    stations = (station *)malloc(sizeof(station));
    char name[32], ch;
    strcpy(name, "Eindhoven");
    int h = 1;
    while(h == 1)
    {
        printf("Command (s/d/p/r/f/q): ");
        scanf(" %c", &ch);
        switch(ch)
        {
            case 's':
                printf("Station: ");
                scanf("%s", name);
                addStation(&stations, &name[0]);
                break;
            case 'q':
                h = 0;
                break;
            case 'p':

                break;
        }
    }
}

我需要为学校编写一个程序,列出火车站及其目的地的链表。这段代码在&#34; if(strcmp(temp-&gt; name,name)== 0)&#34; (第23行)。我已经尝试解决这个问题5个小时但没有任何作用:(。有人知道什么是错的吗?

1 个答案:

答案 0 :(得分:0)

您基本上是设置stations = NULL,然后使用temp执行解除引用的内容。这就是为什么seg错误的原因。不要怪strcmp

if(stations == NULL) // you were assigning here. 
{
    printf("ERROR");
    return NULL;
}

for(temp = stations; temp->next != NULL; temp = temp->next)

很少有事情要注意(良好做法)

不要投放malloc的返回类型。 同时检查malloc的返回值。尝试阅读malloc的参考资料,您就会理解为什么。