Huz*_*uzo 1 c stack struct pointers
所以,我想创建一个堆栈,如下所示:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct node *link;
}node;
typedef struct Stack{
struct Node *topnode;
int count;
}stack;
void push(int data, stack *ourstack){
node newnode;
newnode.data = data;
ourstack.topnode = &newnode;
}
int main()
{
stack mystack;
push(1,mystack);
printf("%d",(mystack.(*topnode).data));
}
Run Code Online (Sandbox Code Playgroud)
但我确实得到了错误.我在这里有点困惑.在push()
函数内部,在最后一行中,我尝试了各种方法来实现它,但每次都失败了.现在,我的想法是,ourstack
指向一个指针struct Stack
.并且topnode
它也是指向另一个节点结构的堆栈结构内的指针.那么,不应该(*ourstack).(*topnode) = newnode
或ourstack.topnode = &newnode
工作?为什么?
既不工作也因为newnode
在堆栈上,一旦代码退出push
,它将不再存在.您需要动态分配它.
void push(int data, stack *ourstack){
node *newnode;
newnode = malloc(sizeof(*newnode));
newnode->next = ourstack->topnode; // Point the next of the new node to the top node of the stack
newnode->data = data;
ourstack->topnode = newnode;
}
Run Code Online (Sandbox Code Playgroud)
而且您还需要mystack
正确初始化,main
否则您topnode
可能会冒未定义的行为风险,NULL
或者它可能具有随机值.
stack mystack;
mystack.topnode = NULL;
mystack.count = 0;
Run Code Online (Sandbox Code Playgroud)