strcmp 给出分段错误

Strcmp gives segmentation 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;
        }
    }
}

我需要为学校编写一个程序,制作一个火车站及其目的地的链接列表。这段代码在 "if(strcmp(temp->name, name) == 0)" 处给我 Segmentation Fault(第 23 行)。我已经尝试修复此问题大约 5 个小时,但没有任何效果:(。有人知道出了什么问题吗?

您基本上是在设置 stations = NULL,然后使用 temp 取消引用它。这就是段错误的原因。不要责怪strcmp

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

还有

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

注意事项(良好做法)

不要转换 malloc 的 return 类型。 还要检查 malloc 的 return 值。尝试阅读 malloc 的参考资料,您就会明白为什么。