Count number of cells in a chained list

Asked

Viewed 716 times

2

I made the following code to count the number of cells in a chained list. But it is giving segmentation failure (use Linux). I wish someone would help me.

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

typedef struct registro celula;
struct registro
{
    int x;
    celula *prox;
};

void insere(int n, celula *p);
void contaRecursiva(celula *p);

int main()
{
    int n1;
    celula atual;
    int tecla = 10;
    celula *pointer;

    pointer = &atual;

    while(tecla != 0)
    {
        printf("====== MENU ======\n");
        printf("1 - para inserir um número\n");
        printf("2 - para ver a quantidade de elementos\n\n");
        scanf("%d", &tecla);
        getchar();
        printf("\n");

        if(tecla == 1)
        {
            printf("Digite um numero\n");
            scanf("%d", &n1);
            getchar();
            insere(n1, &atual);
            printf("\n");
        }
        else if(tecla == 2)
        {
            contaRecursiva(&atual);
        }
    }
}

void insere(int n, celula *p)
{
    celula *nova;
    nova = (celula *) malloc(sizeof(celula));
    nova->x = n;
    nova->prox = p->prox;
    p->prox = nova;
}

void contaRecursiva(celula *p)
{
    int numCel;
   if(p != NULL)
   {
       numCel++;
       contaRecursiva(p->prox);
   }
   printf("%d celulas", numCel);
}

2 answers

2

Segmentation failure occurs because you did not initialize the "current.Prox" field when you declared the "current" variable".

int main()
{
  int n1;
  celula atual;
  int tecla = 10;
  celula *pointer;

  atual.prox = NULL; // <------------------- faltou
  pointer = &atual;

Note that this solves the problem of segmentation failure, I did not analyze the logic of your program.

-1

Solve the segmentation fault problem. I have a simpler problem. I have to create a recursive function that counts the number of cells.

contaRecursiva(celula *p, int cont2)

{ int cont = cont2; cellula *aux = p; if(aux != NULL) {
accountRecursive(aux->Prox, cont2++); } printf("%d cellulae", cont); }

  • Ideally you answer this question (or accept the other answer if you are right) and create a new post with the new question, the chance that this question will not be answered is great.

Browser other questions tagged

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