Pure C chained list error

Asked

Viewed 35 times

-1

I am making a simple chained list where struct has only one 'given' integer variable, the user type the data to be inserted right into the menu and it is played in the function that adds a new element at the beginning of my chained list. But he keeps throwing the bug that new element has not yet been initialized, just on the line where he receives the die.

/*corpo da minha struct
struct lista
{
    int dado;
    lista* proximo;
}; */


void inserir_inicio(int numero)
{
    lista* novo_elemento;

    novo_elemento->dado = numero; // onde acontece o erro using uninitialized memory

    if (head == NULL)
    {
        head = novo_elemento;
        head->proximo = NULL;
    }
    else
    {
        novo_elemento->proximo = head;
        head = novo_elemento;
    }
}
  • Yes, novo_elemento is a pointer to lista. Store memory for struct (see malloc function).

1 answer

1


You just declared the pointer new_element, missing to allocate memory to this pointer.

novo_elemento = (lista*) malloc(sizeof(lista));
  • 2

    malloc returns a pointer of the type void, have to make a cast for die pointer type

Browser other questions tagged

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