[英]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.