2016-01-20 62 views
0

iam試圖在C中使用一個簡單的鏈表,但我有一些麻煩。 我創建了一個結構節點鏈接列表的意外行爲

struct node{ 
    int value; 
    struct node *next; 
}; 

,並在主下面的代碼

struct node *root; 
struct node *conductor; 

root = (struct node *)malloc(sizeof(struct node)); 
root->next = 0; 
conductor = root;  

root->value = 1; 

if ((root->value) == 1) 
    LED_GREEN = 1; 
//LED_GREEN = 1; 

我運行它在嵌入式系統上寫道,只是比較根節點的值。我期望LED發光,但事實並非如此。任何人有一個想法,爲什麼這不按預期工作?

+1

什麼是LED_GREEN?另請[閱讀本文](http://stackoverflow.com/a/605858/1983495)。如果你不使用'if'會發生什麼? –

+0

root-> next = 0;是錯的。它應該指向有效的內存位置 – JerryGoyal

+1

@JerryGoyal它怎麼錯了?這就是你如何初始化第一個節點的鏈表。 – Lundin

回答

0

@ xy36是對的,而且這個錯誤不能在發佈的代碼中複製。但是,如果你需要一個列表,你可以使用下面的代碼。我只是改進了一點你的代碼。關於var LED_GREEN,如果你想改變它的值,我建議你改變函數addNode中的代碼。如果你使用的是arduino這樣的embbed板,只需檢查你的電線連接,不要忘記使用命令「digitalWrite(pin,value);」來改變你的價值。

祝你好運。

#include <stdio.h> 
#include <stdlib.h> 

struct node{ 
    int ID; 
    int value; 
    struct node *next; 
}; 

int LED_GREEN = 0; 

struct node * addNode(struct node *conductor, int value){ 
    struct node * newNode; 
    newNode = (struct node *)malloc(sizeof(struct node)); 
    newNode->value = value; 
    newNode->ID = conductor->ID + 1; 
    conductor->next = newNode; 
    newNode->next = NULL;  
    printf("Node added.\n"); 
    return newNode; 
} 

void printList(struct node *root){ 
    struct node *conductor = NULL; 
    conductor = root; 

    while(conductor){ 
     printf("Node[%d] value: %d. \n",conductor->ID, conductor->value); 
     conductor = conductor->next; 
    } 
    return; 
} 

int main() 
{ 
    struct node *root =NULL; 
    struct node *conductor = NULL; 

    if(!root){ 
     root = (struct node *)malloc(sizeof(struct node)); 
     root->next = 0; 
     conductor = root;  
     root->value = 1; 
     root->ID = 0; 
    } 

    conductor = addNode(conductor, 3); 
    conductor = addNode(conductor, 5); 
    conductor = addNode(conductor, 7); 
    conductor = addNode(conductor, 11); 
    conductor = addNode(conductor, 13); 

    printList(root); 
    return 0; 
} 
2

我自己解決了這個問題,但也許它對類似問題有幫助,當我發佈解決方案。通過更改我的IDE的項目選項中的堆大小來解決問題。大小設置爲0,因此malloc無法分配內存。

+0

這應該讓你記得總是檢查' malloc' - 我敢打賭它在堆大小爲0時返回NULL? –

+0

當然它;-) – xy36

+0

但我從IDE的支持得到了一些幫助。通常應該有鏈接錯誤導致堆大小丟失,但事實並非如此。無論如何,感謝您的幫助! – xy36