2013-07-23 84 views
1

大家好我有我的C代碼的這個問題。 我正在實現一個堆棧,每當我彈出它改變函數彈出堆棧,但不是原來的堆棧。 請幫忙。如何通過引用傳遞結構並更改其值

這裏是我的代碼

char pop(Node* top) 
{ 
    char result ; 

    if (size == 0) // The stack is empty. 
    { 
     return '\0' ; 
    } 

    else //The stack contains at least one element . 
    { 
     result = top->opp ; 
     top = top->next ; 
    } 

    size-- ; 

    return result; 
} 
+0

通過查看代碼,我建議你做一些編輯1.你不會刪除在開始時傳給你的'top',所以它是內存泄漏,2.因爲它是堆棧,你不需要'size' ,你可以簡單地檢查'if(top!= NULL)'表示堆棧不是空的... – Opsenas

回答

0

我們需要更多的代碼,但我會嘗試:

我猜你使用該功能是這樣的:

char pop(Node* top) 
{ 
    char result ; 

    if (size == 0) // The stack is empty. 
    { 
     return '\0' ; 
    } 

    else //The stack contains at least one element . 
    { 
     result = top->opp ; 
     top = top->next ; 
    } 

    size-- ; 

    return result; 
} 

int main() 
{ 
    // this is the top of the stack 
    Node *stack; // let's say there already are some elements in this stack 
    pop(stack); 
    return 0; 
} 

的問題是,你想改變指針值,則stack將指向棧頂。爲了做到這一點,你必須使用一個指針的指針,就像這樣:

char pop(Node** top) 
{ 
    char result ; 
    Node *ptr; 

    ptr = *top; 
    if (size == 0) // The stack is empty. 
    { 
     return '\0' ; 
    } 

    else //The stack contains at least one element . 
    { 
     result = (*top)->opp ; 
     (*top) = (*top)->next ; 
     // You should free the pointer, like user2320537 said in his answer. 
     free(ptr); 
    } 

    size-- ; 

    return result; 
} 

int main() 
{ 
    // this is the top of the stack 
    Node *stack; // let's say there already are some elements in this stack 
    pop(&stack); // You give the pointer address 
    return 0; 
} 
+0

非常感謝你:)。 問題解決了。 –

0

嘗試焦炭彈出(節點**頂部)和操作上(*頂部)

1

你需要釋放頂部的當前位置也...使用免費as

Node *ptr; 

ptr = top; 

if (size == 0) // The stack is empty. 
    { 
     return '\0' ; 
    } 

    else //The stack contains at least one element . 
    { 
     result = top->opp ; 
     top = top->next ; 
    } 

    free(ptr); 

========================================== =======================

稱之爲

int main(){ 
Node front = NULL: 

// place your code of PUSH here. 

pop(&front); // will call the function **pop** 

} 

}

+0

你認爲他沒有在他的代碼中使用free ... –

0

如果你改變你傳遞一個指針的變量(其地址)的值的函數 如

void increment(int *p) { 
     p += 1; 
} 

同樣改變指針的值,你需要一個指針傳遞給函數指針

char pop(Node **top) { 
     char t; 
     Node *p; 
    if(size == 0) { 
     return '\0'; 
    } else { 
     p = *top; 
     t = p->op; 
     (*top) = (*top)-> next; 
     free(p); 
     return t; 
    } 
} 
0

請把上面的指針引用流行的功能就像是「字符pop(Node ** top){}「並添加改變你的else塊」top [0] = top [0] - > next;「而不是「top = top-> next」。

相關問題