2014-03-06 34 views
0

我正在研究一個代碼,該代碼需要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

+3

你不能 「分配」 到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

+0

並選擇一種語言。我完全沒有看到C++標準庫或語言特定的功能。如果這是C,則放棄C++標記。 – WhozCraig

+0

假設這是嚴格的c代碼而不是C++,你可以輸入def char * AirportCode,然後讓你的init函數創建AirportCodes malloc 4字符,但是這是c還是C++? –

回答

0

你不能像這樣將char數組賦值給對方(即使可以,也不會有我相信你期待的結果)。我想你想要做的是字符串分配?然後,考慮到您使用C++,您應該將AirportCode定義爲std::string而不是char[4]

+0

但是,如果它只有C(如你的評論所述),那麼你不能使用'std :: string',而應該使用'strncpy'或一個硬編碼的逐字節拷貝,如WhozCraig。 – Supernormal

0

嘗試這種

void insertFirst(AirportCode code, Node **listPtr) { 
    Node* head = *listPtr; 
    Node* temp = newNode(code); 
    temp->next = head; 
    *listPtr = temp; 
}