How to allocate a dynamic stack, with size provided by the user?

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

#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;
}
Author: Maniero, 2017-12-10

1 answers

Not so. If it is a stack then it would be something like this:

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

You don't need anything else but to decide what to do if you give allocation error (which is wrong in the function presented in the question. You allocate space for the entire stack, that is, you have space for each of the elements you can put in it.

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

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

Would also need to address the error, which is wrong in the question.

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

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

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

 2
Author: Maniero, 2020-07-06 14:22:40