2015-02-07 23 views
0

對於下列功能:指針不採取新的價值

/*this function removes the topmost item in the stack*/ 
void pop(Stack * S, NODE * returnNode) { 
    stackNode * temp; 

    if(S->root == NULL) { 
     ERROR("Sorry, cannot pop an empty stack!!\n"); 
    } 
    else { 
      temp = S->root; 
      returnNode = temp->Item;/*x now points to the topmost node*/ 
      S->root = temp->nextItem;/*stack points to the rest of the list*/ 
      free(temp);/*returning memory to the system*/ 
    } 
} 

我期待returnNode指針具有相同的值作爲temp->Item,但是當我在GDB檢查值沒有。我錯過了什麼嗎?

我應該補充temp值正在正確設置。

+0

C是仍調用 - 值。沒有例外。 – Deduplicator 2015-02-07 20:47:22

+0

爲什麼地獄人們會投下他們可能會遇到的每個問題?停止與你的傲慢,只因爲你知道C並不意味着你必須投票否決其他人的問題,多麼無用的態度 – Mcs 2015-02-07 21:10:54

回答

1

認爲它這樣,

的功能,只能修改指針本身的指針指向,而不是值的變量,即一個地址。如果你想修改一個指針的值,你需要傳遞一個指向它的指針。

例如

如果您有:

int k = 5, f = 15, *pk = &k, *pf = &f; 

,並要切換的pk和PF值,就需要這樣的功能:

void change (int **m, int **n) { 
    int *help = *m; 
    *m = *n; 
    *n = help; 
} 

change(&pk, &pf); 
printf("pk ist %i, pf ist %i\n", *pk, *pf); 
/* pk ist 15, pf ist 5;*/ 
2

如果你想更新指針作爲參數,你需要傳遞它的地址。否則,您只需更新調用堆棧上的值,該值位於本地範圍內。

void pop(Stack * S, NODE ** returnNode) { 
    stackNode * temp; 

    if(S->root == NULL) { 
     ERROR("Sorry, cannot pop an empty stack!!\n"); 
    } 
    else { 
      temp = S->root; 
      *returnNode = temp->Item;/*x now points to the topmost node*/ 
      S->root = temp->nextItem;/*stack points to the rest of the list*/ 
      free(temp);/*returning memory to the system*/ 
    } 
} 
+0

更好的選擇是使用返回值, – Deduplicator 2015-02-07 20:49:27

1

你應該有*returnNode = temp->Item;,而不是returnNode = temp->Item;