使用鏈表處理 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;
}
}
uj5u.com熱心網友回復:
您遇到分段錯誤,因為您的代碼正在取消參考NULL指標。
在這里,指標head分配NULL:
Pokemon *head = NULL;
然后tempPointer被分配head:
Pokemon *tempPointer = head;
然后tempPointer在這里取消參考:
while (tempPointer->next != NULL)
可能您想將NewPokemonNode()函式的回傳值分配給head指標。但請注意,如果失敗,NewPokemonNode()函式也可能回傳。所以你也應該注意這一點。將回圈條件更改為。NULLmalloc()whiletempPointer != NULL
Pokemon *head = NULL;
head = NewPokemonNode("Bulbasaur", "Grass", "Overgrow");
Pokemon *tempPointer = head;
while (tempPointer != NULL)
{
printf("Working");
tempPointer = tempPointer->next;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/412251.html
標籤:
上一篇:ANSIC-為什么malloc和free不適用于char指標?
下一篇:對指標索引運算子的困惑
