簡體   English   中英

嘗試打印出鏈表時出現分段錯誤

[英]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() function 的返回值分配給head指針。 但請注意, NewPokemonNode() function 也可能返回NULL ,以防malloc()失敗。 所以你也應該注意這一點。 while循環條件更改為tempPointer != NULL

    Pokemon *head = NULL;

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM