如何通过引用传递结构并更改其值

时间:2013-07-23 07:13:05

标签: c function pointers reference stack

大家好,我的C代码存在这个问题。 我正在实现一个堆栈,每当我弹出它时,它会更改函数pop中的堆栈,但不会更改原始堆栈。 请帮忙。

这是我的代码

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;
}

5 个答案:

答案 0 :(得分:1)

您还需要释放顶部的当前位置...免费使用

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**

}

}

答案 1 :(得分:0)

尝试使用char pop(Node ** top)并操作(* top)

答案 2 :(得分: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;
}

答案 3 :(得分:0)

如果更改变量的值,则将指针(其地址)传递给函数 例如

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

类似于更改POINTER的值,您需要将指针传递给指向函数的指针

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;
    }
}

答案 4 :(得分:0)

请将顶部指针的引用发送到pop函数,如“char pop(Node ** top){}”并添加更改你的其他块“top [0] = top [0] - > next;”而不是“top = top-> next;”。