尝试将值分配给链接列表时,不兼容的类型错误

时间:2014-03-06 05:19:11

标签: c++ struct linked-list

结构是:

typedef AirportCode[4];
typedef struct node{
     AirportCode airport;
     struct node *next;
}Node;

现在我要做的是:

void insertFirst(AirportCode code, Node **listPtr){
     if (*listPtr == NULL)
      {
       (*listPtr)->airport = code;
       (*listPtr)->next = NULL;
      }

我收到的错误消息是:

  从类型'char *'

分配类型'AirportCode'时,

不兼容的类型

1 个答案:

答案 0 :(得分:0)

typedef AirportCode[4];

这是无效的C ++,它应该是char的数组吗?

typedef char AirportCode[4];

数组类型的函数参数衰减为指针,因此code参数的类型为char*,并尝试将其分配给数组,这是不允许的。您可能希望复制每个字符,而不是尝试分配整个数组:

memcpy(*listPtr)->airport, code, sizeof(AirportCode));

AirportCode typedef替换为代表机场代码的类可能更好:

struct AirportCode
{
    char code[4];
};

这样做会使它成为第一类,而不仅仅是数组的typedef,这意味着参数传递和赋值按预期工作:

(*listPtr)->airport = code;

另外,作为一种风格,你不需要在C ++中使用strde的typedef,所以你可以将Node定义为:

struct Node{
     AirportCode airport;
     Node* next;
};
相关问题