#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char String[256];
typedef struct LinkedListNode {
String Name;
struct LinkedListNode * Next;
struct LinkedListNode * Friend;
} Node;
typedef Node * NodePointer;
NodePointer InputData(NodePointer Head) {
String PersonName;
NodePointer Person;
int StringLength;
String FormattedName;
do {
printf("Enter nation name :");
fgets(PersonName,256,stdin);
if (PersonName[0] != '\n') {
Person = (NodePointer)malloc(sizeof(NodePointer));
//copy all except trailing \n
strncpy(Person->Name, PersonName, strlen(PersonName)-1);
Person->Next = Head;
Person->Friend = NULL;
Head = Person;
}
} while (strcmp(PersonName, "\n"));
return Head;
}
void InputAllies(NodePointer Head) {
String AllyName;
NodePointer Ally;
String FormattedName;
do {
printf("Enter best ally for %s :", Head->Name);
fgets(AllyName,256,stdin);
if (AllyName[0] != '\n') {
Ally = (NodePointer)malloc(sizeof(NodePointer));
//copy all except trailing \n
strncpy(Ally->Name, AllyName, strlen(AllyName)-1);
Head->Friend = Ally;
Head = Head->Next;
}
} while (Head != NULL);
}
段错误的部分具体是 InputAllies() 函数,并且仅适用于具有 5 个或更多元素的列表。我真的不知道发生了什么,但我认为这与我的字符串的大小有关。降低 typedef String 的大小仅在 3 个元素后导致段错误。