从C中的函数推入堆栈
在我的testfunction中,我试图将两个值推入堆栈。它在main()中工作得很好,但我认为在使用testfunc()时,我把指针弄乱了 这些值到达push()函数,但这些值根本不会出现在我的堆栈中 提前谢谢你的帮助从C中的函数推入堆栈,c,function,pointers,stack,push,C,Function,Pointers,Stack,Push,在我的testfunction中,我试图将两个值推入堆栈。它在main()中工作得很好,但我认为在使用testfunc()时,我把指针弄乱了 这些值到达push()函数,但这些值根本不会出现在我的堆栈中 提前谢谢你的帮助 struct StackNode { unsigned int data; struct StackNode* next; }; struct StackNode* newNode(unsigned int data)
struct StackNode
{
unsigned int data;
struct StackNode* next;
};
struct StackNode* newNode(unsigned int data)
{
struct StackNode* stackNode =
(struct StackNode*) malloc(sizeof(struct StackNode));
stackNode->data = data;
stackNode->next = NULL;
return stackNode;
}
int isEmpty(struct StackNode *root)
{
return !root;
}
void push(struct StackNode** root, unsigned int data)
{
struct StackNode* stackNode = newNode(data);
stackNode->next = *root;
*root = stackNode;
printf("%u pushed to stack\n", data);
}
void pop(struct StackNode** root)
{
if (isEmpty(*root))
printf("ERROR");
struct StackNode* temp = *root;
*root = (*root)->next;
free(temp);
}
unsigned int peek(struct StackNode* root)
{
if (isEmpty(root))
return -2;
return root->data;
}
void testfunc(struct StackNode* root, unsigned int a, unsigned int b)
{
struct StackNode *r=root;
push(&r, a);
push(&r, b);
}
主要
intmain()
{
struct StackNode*root=NULL;
push(&root,0);//工作正常并将“0”推送到堆栈中。
testfunc(root,12,15);//您的push
函数修改根:
*root = stackNode;
在您的testfunc
中,此更改是对函数本地的root
变量进行的。也就是说,对它的任何更改都不会在调用函数(main
)中可见。因此,从main
的角度来看,似乎没有任何更改,因为那里的root
变量没有更改
要确保对testfunc
中的root
的更改在main
中也可见,您可以返回它:
struct StackNode* testfunc(struct StackNode* root, unsigned int a, unsigned int b)
{
push(&root, a);
push(&root, b);
return root;
}
root = testfunc(root, 12, 15);
或者,您也可以:
void testfunc(struct StackNode** root, unsigned int a, unsigned int b)
{
push(root, a);
push(root, b);
}
testfunc(&root, 12, 15);
您的push
函数修改根目录:
*root = stackNode;
在您的testfunc
中,此更改是对函数本地的root
变量进行的。也就是说,对它的任何更改都不会在调用函数(main
)中可见。因此,从main
的角度来看,似乎没有任何更改,因为那里的root
变量没有更改
要确保对testfunc
中的root
的更改在main
中也可见,您可以返回它:
struct StackNode* testfunc(struct StackNode* root, unsigned int a, unsigned int b)
{
push(&root, a);
push(&root, b);
return root;
}
root = testfunc(root, 12, 15);
或者,您也可以:
void testfunc(struct StackNode** root, unsigned int a, unsigned int b)
{
push(root, a);
push(root, b);
}
testfunc(&root, 12, 15);
简单地说:除非您打算通过该参数返回指针,否则永远不要使用指针到指针。而且没有真正的理由需要传递StackNode**
。最好将所有分配和硬拷贝放在堆栈ADT中,而不向调用方公开任何内部内容。简单地说:永远不要使用指针到p除非您打算通过该参数返回指针。而且没有真正的理由需要传递StackNode**
。最好将所有分配和硬拷贝放在堆栈ADT中,而不向调用方公开任何内部内容。Sander是正确的。a面..我还想指出,peek
函数正在将负数返回到无符号int
。编译器应该对此发出警告。非常感谢,根据您的建议进行了处理。无论如何,我可能会像Lundin所写的那样放弃指向指针的指针编辑:哦,谢谢dutchRooster,我知道:)Sander是正确的。a面..我也会指出您的peek
函数正在将负数返回到unsigned int
。您的编译器应该对此发出警告。非常感谢,根据您的建议进行了处理。无论如何,我可能会像Lundin所写的那样完全摆脱指向指针的指针编辑:哦,谢谢dutchRooster,我知道:)