开发者

Stack implementation in C

开发者 https://www.devze.com 2023-01-15 04:08 出处:网络
typedef struct pilha Pilha; struct pilha { char metodo[31]; Pilha *next; }; void create_empty开发者_JS百科_stack(Pilha *Stack)
typedef struct pilha Pilha;

struct pilha
{
    char metodo[31];
    Pilha *next;
};

void create_empty开发者_JS百科_stack(Pilha *Stack)
{
    Stack->next = NULL;
}

int main()
{
    Pilha *Stack;

    create_empty_stack(Stack);
}

Gives me an execution error.

What's the problem with this function?


This is a classic mistake that beginners do.

Let's take a look at your main function:

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

    create_empty_stack(Stack);
}

If you remember pointers, the declaration Pilha* Stack; makes Stack be a memory pointer. But right now it doesn't point to anything, because you did not reserve memory for an object of type Pilha!

Your program crashes because create_empty_stack() tries to access next, a member of this object (remember that this object still doesn't exist).

So, what you should be doing instead is:

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

Or a much simpler approach:

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


you'd better create your function like this:

Pilha* create_empty_stack()
{

    Pilha *Stack = malloc(sizeof(Pilha))
    Stack->next = NULL;
    return Stack;
}


You are passing an uninitialized variable Stack into the function Criar_Pilha_vazia. It will crash as soon as you do the first dereference on Stack in your function.


Consider what Stack points to at the line in Criar_Pilha_vazia(). The dereference for assignment points to a random place. In a virtual memory environment, it will segfault.

0

精彩评论

暂无评论...
验证码 换一张
取 消