C structure to be dynamically allocated

Asked

Viewed 28 times

1

I’m needing it to be dynamically allocated but I’m not finding the problem.

#include <stdio.h>
#include <stdlib.h>
#define tam 10

typedef struct pilha{
    char dado[tam];
    int pos;
}Pilha;

Pilha *p=(Pilha*)malloc(sizeof(Pilha));

void push(char valor){
    p->dado[p->pos]=valor;
    p->pos++;
}

void pop(){
    p->dado[--p->pos];
}

int size(){
    return p->pos;
}

int main(){

    push("d");
    push("b");
    pop();

    printf("Tamanho da pilha é: %d",size());
    return 0;
}
  • Have you tried putting this Pilha *p=(Pilha*)malloc(sizeof(Pilha)); in the main function? And also put a ponteiro stack as function parameter? Example: void push(char valor) leave it like this void push(Pilha *p, char valor). Make these changes that will work.

  • I’ll do that, thank you very much for the tip!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.