问题是你不能在C 中分配数组。您只能初始化它们。此外,您不能将数组传递给函数 - 实际上传递的是指向数组第一个元素的指针。以下声明
typedef char AirportCode[4];
定义AirportCode 类型char[4] - 一个4 字符数组。在您的函数insertFirst 中,您将code 类型为char * 分配给(*listPtr)->airport 类型为AirportCode 或char[4]。这两个是不兼容的类型,因此您会收到错误消息。
由于你不能将数组传递给函数,你应该做的是传递一个指向数组第一个元素的指针和数组长度。然后将数组复制到结构体的对应成员中。
以下三个声明完全相同。函数中的数组参数实际上是一个指向字符的指针。
void insertFirst(AirportCode code, Node **listPtr);
void insertFirst(char code[4], Node **listPtr);
void insertFirst(char *code, Node **listPtr);
另外,您不应该转换malloc 的结果。不要让typedef 混淆命名空间并造成混乱。在这种情况下,没有它你会更好。如果if 条件*listPtr == NULL 是true,那么您正在取消引用块中的空指针,这显然是一个错误。
if(*listPtr == NULL) {
// the below statements dereference the null pointer
// which is an error and would cause program crash
// due to segfault.
(*listPtr)->airport = code;
(*listPtr)->next = NULL;
}
从您的else 块中,我假设您正在尝试在链表的开头添加一个新节点。我建议进行以下更改(感谢 Jonathan Leffler)。
typedef struct node {
char airport[4]; // no typedef. explicit array declaration.
struct node *next;
} Node;
void insertFirst(char *code, Node **listPtr) {
Node *oldHead = *listPtr;
Node *newNode = malloc(sizeof(Node));
if(newNode == NULL) { // check for NULL
printf("Not enough memory to allocate\n");
return;
}
// if the struct member code is a string, then use strncpy to
// guard against buffer overrun, else use memcpy to copy
// code to airport. this is assuming that the buffer pointed
// to by code is never smaller than sizeof newNode->airport
memcpy(newNode->airport, code, sizeof newNode->airport);
newNode->next = oldHead;
*listPtr = newNode; // make listPtr point to the new head
}