C中的堆栈实现

Dio*_*ogo 2 c stack

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);
}
Run Code Online (Sandbox Code Playgroud)

给我一个执行错误.

这个功能有什么问题?

kar*_*lip 12

这是初学者所犯的经典错误.

我们来看看你的主要功能:

int main()
{
    Pilha* Stack; // This line is your problem!

    create_empty_stack(Stack);
}
Run Code Online (Sandbox Code Playgroud)

如果你记得指针,声明Pilha* Stack;会使Stack成为一个内存指针.但是现在它并没有指向任何东西,因为你没有为Pilha类型的物体保留记忆!

您的程序崩溃,因为create_empty_stack()尝试访问一个,该对象的成员(请记住该对象仍然不存在).

所以,你应该做的是:

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);
}
Run Code Online (Sandbox Code Playgroud)

或者更简单的方法:

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); 
}
Run Code Online (Sandbox Code Playgroud)