How to Insert a String into a Stack with C Language

Asked

Viewed 71 times

0

I am studying language C, I am in the Batteries class, but I have a simple question (I believe)

My code works (as I hope), if I pass the vestments manually, as below:

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

struct Pilha {
    int topo;
    int * proxElemento;
};

void criaPilha (struct Pilha *p){
    p->topo = -1;
    p->proxElemento = (int*) malloc(sizeof(int));
}

void insereItem (struct Pilha *p, char * nome) {
    p->topo++;
    p->proxElemento[p->topo] = nome;
}

int main() {
    struct Pilha *pilhaLivros;
    criaPilha(&pilhaLivros);
    insereItem(&pilhaLivros, "Livro 1");
    insereItem(&pilhaLivros, "Livro 2");
    insereItem(&pilhaLivros, "Livro 3");
    return 0;
}

When I change the method of inserting values in the Stack, by a scanf or gets(as below), there is no error in the insertion itself, the data is received and inserted by the inserts functionItem

int main() {
    char * nome;
    struct Pilha *pilhaLivros;
    criaPilha(&pilhaLivros);

    printf("Digite o livro 1: ");
    scanf("%s", nome);
    insereItem(&pilhaLivros, nome);

    return 0;
}

or

int main() {
    char * nome;
    struct Pilha *pilhaLivros;
    criaPilha(&pilhaLivros);

    printf("Digite o livro 1: ");
    fflush(stdin);
    gets(nome);
    insereItem(&pilhaLivros, nome);

    return 0;
}

But the contents stored in p->proxElemento[p->topo] was not read by the variable name.

How can I solve this problem?

thank you

  • There are some problems in your code (how to pass an address of a ponteiro instead of an address of a struct Pilha). You apparently create a vector of int to store a string in each position, this will not work, make a matrix of char. Do not use the fflush with stdin as an argument.

  • Hi Julio, thanks for the help, I understand what you’re saying, but in order to better understand my code, I would like (if possible) you to explain it to me, because when I send the direct string it works perfect, but when I pass the string through the read variable, it doesn’t work

1 answer

1

Your code that you say works doesn’t work, on your machine it may seem to work, but it doesn’t do what you really want (the code generates several warning and that means your program will run inconsistently).

Problems

Pass an address of a ponteiro

Problem

Look at your functions:

void criaPilha (struct Pilha *p)
void insereItem (struct Pilha *p, char * nome)

They both need an address struct Pilha, however you are passing an address of a ponteiro of the kind struct Pilha. Observe:

struct Pilha *pilhaLivros; /* pilhaLivros eh um ponteiro */
criaPilha(&pilhaLivros) /* logo voce esta passando um endereco de um ponteiro */

Solution

To solve this it is enough that pilhaLivros is not declared as a pointer, thus:

struct Pilha pilhaLivros; /* agora pilhaLivros nao eh um ponteiro */

Use a vector of int to store string

Problem

You apparently create a vector of int to store a string in each position, observe:

struct Pilha {
    int topo;
    int * proxElemento; /* aqui eh seu ponteiro que vai usar como se fosse um vetor */
};



/* aqui eh na funcao criaPilha */
p->proxElemento = (int*) malloc(sizeof(int)); /* entao voce aloca memoria */



/* aqui eh na funcao insereItem */
p->proxElemento[p->topo] = nome; /* e coloca cada string em uma posicao dele */

Here we have some problems.

Use a vector of int to store string

A vetor of int serves to store several variables of type int, if you want to store float, then the vector has to be float and that logic goes to any kind. We don’t have something like this:

string vetor[10];

To create a vector of string we need to remember that a string is already a vector, so a vector of string is a vector of vectors (a matrix).

struct Pilha {
    int topo;
    int * proxElemento; /* isso aqui precisa ser uma matriz de char */
    char proxElemento[5][10]; /* uma matriz de char eh o que voce precisa */
};

The above matrix can store 5 string, where each of them cannot overcome 10 size. To create an array with dynamic allocation we need a ponteiro of ponteiro, notice:

struct Pilha {
    int topo;
    char **proxElemento; /* vamos usar o malloc para criar uma matriz */
};
Creating an array using pointer

In the malloc we should inform the size of bytes which we will allocate. If you want a matrix that has 10 string then we should put the value 10 in malloc. Example:

p->proxElemento = (int*) malloc(sizeof char * 10);
p->proxElemento = malloc(10); /* char vale 1 byte entao o sizeof nao eh necessario, a conversao tambem nao eh necessaria */

Your function creationPilha would look like this:

void criaPilha (struct Pilha *p){
    p->topo = -1;
    p->proxElemento = malloc(10);
}

Now we can have 10 string different.

Adding a string

Notice how you were adding an array:

void insereItem (struct Pilha *p, char * nome) {
    p->topo++;
    p->proxElemento[p->topo] = nome;
}

Remember that we cannot directly assign a string, see:

a  = 10; /* valido */
b = 4.7; /* valido */
c = "teste"; /* invalido */

We can copy a string in another using strcpy. Then the insert function would look like this:

void insereItem (struct Pilha *p, char * nome) {
    p->topo++;
    strcpy(p->proxElemento[p->topo], nome);
    /* p->proxElemento[p->topo] = nome; */
}

But before doing this it is necessary to allocate how many bytes our string need to have, like this:

void insereItem (struct Pilha *p, char * nome) {
    p->topo++;
    p->proxElemento[p->topo] = malloc(31); /* agora voce pode adicionar um string com ate 30 de tamanho */
    strcpy(p->proxElemento[p->topo], nome);
    /* p->proxElemento[p->topo] = nome; */
}

Ideally you check the size of the string nome and allocate only the necessary (don’t forget to leave 1 more space for the \0).

With these changes your code should work, you can put a scanf that will work normally.

See your code working here.

OBS

Don’t forget to use the free to free up memory when deleting a string or when to destroy the pilha.

You can create a variable of type int within your struct to store how many string your battery can store and thus maintain control.

Browser other questions tagged

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