尝试打印链表时出现分段错误

Segmentation error when trying to print out a linked list

使用链接列表处理 pokedex 项目,在创建节点并尝试打印后出现此错误我是 C 的新手,所以如果这是一个愚蠢的错误,我不会感到惊讶。

signal: segmentation fault (core dumped)

这是我的代码

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

typedef struct Pokemon {
  char pokemonName[50];
  char pokemonType[20];
  char pokemonAbility[50];

  struct Pokemon *next;
} Pokemon;

Pokemon* NewPokemonNode(char pokemonName[50],char pokemonType[20], char pokemonAbility[50]) {

  Pokemon *new_node = NULL;
  new_node = malloc(sizeof(Pokemon));

  if (new_node != NULL){

    strcpy(new_node -> pokemonName, pokemonName);
    strcpy(new_node -> pokemonType, pokemonType);
    strcpy(new_node -> pokemonAbility, pokemonAbility);

    new_node->next = NULL;   
  }
  return new_node;
}

int main(void){
  Pokemon *head = NULL;

  NewPokemonNode("Bulbasaur", "Grass", "Overgrow");
  
  Pokemon *tempPointer = head;
  while (tempPointer->next != NULL)
  {

    printf("Working");

    tempPointer = tempPointer->next;

  }

}

您遇到分段错误是因为您的代码正在取消引用 NULL 指针。
这里,指针 head 赋值 NULL:

  Pokemon *head = NULL;

然后 tempPointer 被赋值 head:

  Pokemon *tempPointer = head;

然后在此处取消引用 tempPointer

  while (tempPointer->next != NULL)

您可能希望将 NewPokemonNode() 函数的 return 值分配给 head 指针。但请注意,NewPokemonNode() 函数也可能 return NULL,以防 malloc() 失败。所以你也应该注意这一点。将 while 循环条件更改为 tempPointer != NULL.

    Pokemon *head = NULL;

    head = NewPokemonNode("Bulbasaur", "Grass", "Overgrow");

    Pokemon *tempPointer = head;
    while (tempPointer != NULL)
    {
        printf("Working");
        tempPointer = tempPointer->next;
    }