c-尝试打印链接列表时出现分段错误



使用链表处理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;

然后将CCD_ 4分配给head:

Pokemon *tempPointer = head;

然后在此取消引用tempPointer

while (tempPointer->next != NULL)

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

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

最新更新