我正在研究一個代碼,該代碼需要3個機場代碼並將它們變成節點,然後將它們添加到列表中。以下是我迄今爲止:在開始處插入節點
void insertFirst(AirportCode code, Node **listPtr) {
/* IMPLEMENT */
//needs to add code to list, then change the head pointer
Node* head;
head = NULL;
char tarray[4];
strncpy(tarray, code, 4);
Node* temp = (Node*)malloc(sizeof(Node));
temp->airport = tarray;
temp->next = head;
head = temp;
}
/* defined types:
AirportCode is an alias for a 4-char array
Node is a linked list node (struct) for AirportCodes */
typedef char AirportCode[4];
typedef struct node {
AirportCode airport;
struct node *next;
} Node;
以下部分不能被改變:
/* newNode - here is a utility function to create a new node;
node's airport set to a copy of code, and next set to NULL;
returns a pointer to the new node */
Node *newNode(AirportCode code) {
Node *node;
if ((node = (Node *)malloc(sizeof(Node))) != NULL) {
strcpy(node->airport, code);
node->next = NULL;
}
else {
fprintf(stderr, "out of memory - terminating\n");
exit(1);
}
return node;
}
每次我嘗試編譯這個使用gcc我得到的錯誤:
array type 'AirportCode' (aka 'char [4]') is not assignable I have no idea why this is happening, any help is greatly appreciated
你不能 「分配」 到C.陣列你可以使用['的memcpy()'](http://en.cppreference.com/w/c/字符串/字節/ memcpy)或'strcpy()',但最後代碼只有4個字符寬。硬編碼4個元素作爲分配一個接一個:'temp-> airport [0] = tarray [0]; temp-> airport [1] = tarray [1];'etc ...和['strncpy()'](http://en.cppreference.com/w/c/string/byte/strncpy)可能不會' t按照您的想法工作,所以請仔細閱讀*它的功能。最後,你的第一次插入功能*不會*。它永遠不會觸及傳入的'listPtr',從而泄漏內存並永遠不會更新您的列表。 – WhozCraig
並選擇一種語言。我完全沒有看到C++標準庫或語言特定的功能。如果這是C,則放棄C++標記。 – WhozCraig
假設這是嚴格的c代碼而不是C++,你可以輸入def char * AirportCode,然後讓你的init函數創建AirportCodes malloc 4字符,但是這是c還是C++? –