How to allocate a dynamic, user-supplied stack?

1

I want to allocate a dynamic stack with the size provided by the user, then treat it as a "vector" would be more or less what I did in the function ALOCA ?

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
struct figuras
{
    char nome[100];
    char idade[5];
    char selecao[100];
};
typedef struct elemento* Pilha;

struct elemento
{
    struct figuras dados;
    struct elemento *prox;
};
typedef struct elemento Elem;
//FUNCOES
Pilha* cria_Pilha();


void menu()
{
    printf("1 - Criar Pilha Dinamicamente\n2 - Inserir Elementos\n3 - Remover Elementos\n4 - Imprimir Elementos\n5 - Checar Pilha vazia\n6 - Checar Pilha Cheia\n7 - Destruir Pilha\n");
    printf("Digite uma opcao\n");
}

int main()
{
    int *ptam;
    int tampilha, op;
    do{
    menu();
    scanf("%d", &op);
    if(op == 1)//CRIAR
    {
        system("cls");
        printf("Digite o Tamanho da sua Pilha\n");
        scanf("%d", &tampilha);
        //ptam = &tampilha;
        Pilha *pi = cria_Pilha();
        ALOCA(pi, tampilha);
    }else
        if(op == 2)//PUSh (INSERIR)
        {

        }else
            if(op == 3)//POP(remover1)
            {

            }else
                if(op == 4)//IMRPIMIR
                {

                }else
                    if(op == 5)//Checar pilha vazia
                    {

                    }else
                        if(op == 6)//CHECAR PILHA CHEIA
                        {

                        }else{//DESTRUIR PILHA
                        }



 }while(op != 8);

    return 0;
}



//funcoes escopo
Pilha* cria_Pilha()
{
    Pilha* pi = (Pilha*) malloc(sizeof(Pilha));
    if(pi != NULL){
        *pi = NULL;
    }

    return pi;
}
int ALOCA(Pilha* pi, int tam)
{
    if(pi == NULL)
        return 0;
    Elem* no;
    no = (Elem*) malloc(tam * sizeof(Elem));
    if(no == NULL)
        return 0;
}
    
asked by anonymous 10.12.2017 / 15:23

1 answer

1

Not so. If it's a stack then it would look something like this:

Pilha pi = malloc(sizeof(Elem) * tam);

You need nothing more than to decide what to do if there is an allocation error (which is wrong with the function presented in the question. You allocate space for the entire stack, ie you have room for each of the elements you can put on it.

If you want a linked list, and part of the code indicates this, you just need to do:

Elem *no = malloc(sizeof(Elem));

I would also need to handle the error, which is wrong with the question.

In this case there will be no structure that will support the list, each node in the list is part of it.

The code mixes concepts, you need to decide whether you want a stack or a list.

The code has several other errors. And it can be written much better.

    
11.12.2017 / 16:25