Error in C Stack implementation

Asked

Viewed 46 times

-1

I am typing the code that is presented in a book and compiling gradually. Mistakes happen where they are "//???????????".

Another detail, in the statement of the structure, where we see *Stack, in this structure, by being declared as pointer, I would be passing the address of the variables within the structure, correct?

#include<stdio.h>        
#include<stdlib.h>

typedef char Itemp;      

typedef struct pilha{   
    int max;   
    int topo;  
    Itemp *item;
    
} *Pilha;   

Pilha pilha(int m){  
    Pilha P=malloc(sizeof(struct pilha));//????????  
    P->max=m;  
    P->topo=-1;
    P->item=malloc(m*sizeof(Itemp));//???????????   
    return P;    
}

int vaziap(Pilha P){        
    if(P->topo==-1) return 1;        
    else return 0;        
}

int cheiap(Pilha P){    
    if(P->topo==P->max-1) return 1;    
    else return 0;   
}

void empilha(Itemp x,Pilha P){         
    if(cheiap(P)) puts("pilha cheia!"); abort();        
    P->topo++;        
    P->item[P->topo]=x;        
    
}
  • It would be nice to inform the errors that appear on the screen.

  • I believe the variable P, of type Pliha, must be a global variable and not local to the function pilha. Study the scope of variables.

  • 1

    I guess instead of if(cheiap(P)) puts("pilha cheia!"); abort();, what you wanted was if(cheiap(P)) { puts("pilha cheia!"); abort(); } - The { and the } are very important here.

1 answer

2


Try this:

#include<stdio.h>        
#include<stdlib.h>

typedef char Item_Pilha;      

typedef struct Pilha {
    int max;
    int topo;
    Item_Pilha *item;
} Pilha;

Pilha *criar_pilha(int m) {
    Pilha *p = (Pilha *) malloc(sizeof(Pilha));
    p->max = m;
    p->topo = -1;
    p->item = (Item_Pilha *) malloc(m * sizeof(Item_Pilha));
    return p;
}

int pilha_vazia(Pilha *p) {
    return p->topo == -1;
}

int pilha_cheia(Pilha *p) {
    return p->topo == p->max - 1;
}

void empilhar(Item_Pilha x, Pilha *p) {
    if (pilha_cheia(p)) {
        puts("pilha cheia!");
        abort();
    }
    p->topo++;
    p->item[p->topo] = x;
}

Anyway, don’t try to hide the * with a typedef because this is a very easy way to do stupid things unless you know very well what you are doing and have a very strong reason to do it.

Also, do everything to avoid collision of names, as in your example, pilha was the name of struct, but also the function of creating the stack, and this kind of thing tends to get the compiler confused, or at least whoever tries to read the code will get confused.

And I think those { and } in the if of the stacking function, you had forgotten and with that, the abort(); was outside the if, always being executed.

And take a look too in this answer.

  • I am grateful, if you or anyone has any suggestions of books on data structure I am grateful also!

Browser other questions tagged

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