I hope you can help me visualize the error in the following code.
I've been studying all types of lists lately. In this program I focus on inserting an element at the beginning of a DOUBLY LINKED list. As soon as I started studying these types of lists, I started doing something simple.
The problem is that when executing the program through GDB, a warning appears in the CMD saying that the program has a SEGMENTATIO FAULT in the function that performs the insertion to the list.
The code is shown below.
#include <stdio.h>
#include <stdlib.h>
struct elementos
{
int dato;
struct elementos *anterior;
struct elementos *siguiente;
};
typedef struct elementos Nodo;
void insertarElemento(Nodo **cabeza, int x);
void mostrarElementos(Nodo * cabeza);
int main()
{
Nodo *primero = NULL;
insertarElemento(&primero, 45);
mostrarElementos(primero);
return 0;
}
void insertarElemento(Nodo **cabeza, int x)
{
Nodo *nuevo_nodo = (Nodo*)malloc(sizeof(Nodo));
nuevo_nodo -> dato = x;
nuevo_nodo -> siguiente = *cabeza;
nuevo_nodo -> anterior = NULL;
(*cabeza) -> anterior = nuevo_nodo;
*cabeza = nuevo_nodo;
}
void mostrarElementos(Nodo *cabeza)
{
while(cabeza != NULL)
{
printf("%8d", cabeza -> dato);
cabeza = cabeza -> siguiente;
}
}