Problem decreasing the size of a stack in c

Asked

Viewed 264 times

0

This program is an exercise to work with stacks, it’s all right, but when I decrease the stack size to exclude the last term it appears in the penultimate element of the vector.

#include <stdio.h>
#include <windows.h>

typedef struct viagem {
  char nome[50];
  char uf[2];
}v;

typedef struct pilha{
  int topo;
  int distancia;
  int visitadas;
  v cidades[10];
}p;

void empilhar (p *pilha) {
  int dist;
  system("cls");
  pilha->topo++;
  printf("Cidade destino: " );
  scanf("%[^\n]s",&pilha->cidades[pilha->topo].nome );
  printf("UF: " );
  scanf("%s",&pilha->cidades[pilha->topo].uf );
  printf("Distancia: " );
  scanf("%i",&dist);
  pilha->visitadas++;
  pilha->distancia=pilha->distancia+dist;
}
void desempilhar (p *pilha){
  pilha->topo--;
}
int main (){
  p pilha;
  pilha.topo=-1;
  pilha.visitadas = 0;
  pilha.distancia = 0;
  int flag=1;
  int opc;
  do {
    system ("cls");
    if (pilha.topo == -1) {
      printf("Voce esta em Maringa-Pr !");
    }
    else {
      printf("Voce esta em %s-%s",pilha.cidades[pilha.topo].nome,pilha.cidades[pilha.topo].uf);
    }
    printf("\nVoce visitou %i cidades", pilha.visitadas );
    printf("\nVoce percoreu %ikm\n", pilha.distancia );
    printf("\n1-Avancar");
    printf("\n2-Voltar");
    printf("\n3-Sair");
    printf("\nopcao: " );
    scanf("%i%*c",&opc );
    switch (opc) {
      case 1:
        empilhar (&pilha);
      break;
      case 2:
        desempilhar (&pilha);
      break;
      case 3:
        flag=0;
      break;
    }
  } while(flag);
  printf("Programa finalizado ! " );
  scanf("%*i",&opc);
}
  • 1

    Note that to store 2 characters in a string (UF case) you need to provide space for the terminator character ' 0'. Declare char[3].

  • Perfect ! Thank you very much

  • 1

    The problem is not exactly on the stack, I explain: the stack you implemented stores only the variables v.nome and v.uf, When you pop, this data is updated and the interface correctly informs which city the user is in. However, the stack does not store variables pilha.distancia and pilha.visitadas and as the function desempilhar() does not change these values, when popping, the data remains unchanged.

  • @v.Santos' observation is pertinent

2 answers

1

Good afternoon Wingeds,

I believe there is a conceptual problem in your stack, which, by definition, are data structures LIFO (Last in, first out). They can be implemented, among other forms, through Dynamic vectors and of Chained lists.

In the case that you presented what I could notice is that you are using the instance of a TAD to store data in it, but this conceptually is not a stack.

Illustration of a stack below

inserir a descrição da imagem aqui

Getting back to your problem:

The operations of Insert (Push) and Remove (Pop) on the stack will vary according to the model you are using. In the case of vectors the Pop is through a "Logical Erase", which is to return a position on the "Top" of the stack without necessarily removing the value, and the Push overwriting these previous values or inserting values into empty spaces. In the case of chained lists the Push is through dynamic allocation, famous malloc(), where you will allocate the space of a cell (TAD) and the link at the top of the list, and the Pop occurs through the function free(), where you will free the space allocated to the cell you want to delete, taking care, of course, not to lose the reference of the previous value.

Abstract illustration of Push and Pop

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

If my remark is incorrect and your activity is really to use the instance of your struct to store your data please signal so that I can delete the answer!

Hugs and good studies!

  • I disagree. What defines a stack is not the nature of the vector used in its implementation, but the respect to the logic LIFO. In the present case, the subject who asked the question implemented a static stack - which unfortunately has its problems there - and therefore it makes no sense to use malloc() for dynamic memory allocation.

  • Good afternoon @v.Santos, I think there was a misunderstanding on your part. First: In no time did I say what DEFINES the stack is the use of dynamic vectors, I said they are LIFO type data structures and that CAN BE IMPLEMENTED THROUGH of dynamic vectors, because in fact it is possible. The question about its structure being a pile was due to the fact that the data are not separate to be removed or inserted following the concept I presented. But thanks for the remark, I will edit to make it clearer and avoid future misunderstandings, hugs!

  • I do not believe that this is a case of "disagreement on my part", in fact, I really do not agree with your answer and even after your clarifications I still do not agree. I explain: your references to the implementations of a dynamic stack, at least, do not relate to the question, since it makes no sense to use malloc() and free() in the code presented. And his conception that one should not use an "instance of a struct" to store data in a stack is, to say the least, mistaken. Hugs @H.Lima.

0


Problem 1:

typedef struct viagem {
  char nome[50];
  // char uf[2]; // <-------------- ERRO
  char uf[3];
} v;

Problem 2:

void desempilhar (p *pilha){
  if (pilha->topo >= 0)  // <------- FALTA
    pilha->topo--;
}

And the @v. Santos remark is correct: distance and "visited" should be part of each stack element, not just a value for the whole stack.

Browser other questions tagged

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