gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:54:28 24 4
gpt4 key购买 nike

大家好,我的 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;
}

最佳答案

我们需要更多代码,但我会尝试:

我猜你是这样使用这个函数的:

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

关于c - 如何通过引用传递结构并更改其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17803630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com