结构如下所示:
typedef char AirportCode [4];
typedef struct node {
AirportCode airport;
struct node *next;
}Node;
我的函数如下所示:
void insertFirst(AirportCode code, Node **listPtr){
Node *Holder = *listPtr;
Node *newNode = (Node *)malloc(sizeof(Node));
if (*listPtr == NULL){
(*listPtr)->airport = code;
(*listPtr)->next = NULL; }
else{
*listPtr = newNode;
newNode->airport = code;
newNode->next = holder; }
}
错误信息是:
incompatible types when assigning to type 'AirportCode' from type 'char *'
此错误消息出现在我分配代码值的两行上。
最佳答案
问题是您无法在 C
中分配数组。您只能初始化它们。另外,您不能将数组传递给函数 - 实际上传递的是指向数组第一个元素的指针。以下声明
typedef char AirportCode[4];
定义 char[4]
类型的 AirportCode
类型 - 一个由 4
字符组成的数组。在函数 insertFirst
中,您将 char *
类型的 code
分配给 (*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
,那么您将取消引用 block 中的空指针,这显然是一个错误。
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
block 中,我假设您正在尝试在链接列表的开头添加一个新节点。我建议进行以下更改(感谢 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
}
关于c - 在C中的链表开头插入新节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22216576/