typedef struct pilha Pilha;
struct pilha
{
char metodo[31];
Pilha *next;
};
void create_empty_stack(Pilha *Stack)
{
Stack->next = NULL;
}
int main()
{
Pilha *Stack;
create_empty_stack(Stack);
}
给我一个执行错误。
这个函数有什么问题?
最佳答案
这是初学者常犯的典型错误。
让我们看一下您的主要功能:
int main()
{
Pilha* Stack; // This line is your problem!
create_empty_stack(Stack);
}
如果您还记得指针,声明 Pilha* Stack;
使 Stack 成为内存指针。但是现在它没有指向任何东西,因为你没有为 Pilha 类型的对象保留内存!
你的程序崩溃是因为 create_empty_stack() 试图访问 next,这个对象的成员(记住这个对象仍然不存在)。
所以,你应该做的是:
int main()
{
// Reserve space in memory for one Pilha object and
// make Stack point to this memory address.
Pilha* Stack = (Pilha*) malloc(sizeof(Pilha));
create_empty_stack(Stack);
}
或者更简单的方法:
int main()
{
Pilha Stack; // Declare a new Pilha object
// and pass the memory address of this new object to create_empty_stack()
create_empty_stack(&Stack);
}
关于c - C中的堆栈实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3673501/