i'm having trouble with a farelly simple function, i have to create a linked list with each node storing a character from a string, i made a function for that, however it doesn't seem to do anything at all
this is the function i'm talking about (variable names are in spanish, i'm sorry for that):
struct listaDoble crearMiADN()
{
char miDni[] = "1234";
struct listaDoble listado = crearLista(strlen(miDni));
struct nodo *actual = listado.first;
for(int i = 0; i<strlen(miDni); i++)
{
if(miDni[i] != '\0' && miDni[i] != EOF)
{
actual->tuNombre[0] = miDni[i];
actual->tuNombre[1] = '\0';
actual = actual->next;
}
}
return listado;
}
and this is the function crearLista
which works but you will probably need it to understand my code:
struct listaDoble crearLista(int num_nodos)
{
struct listaDoble *result = (struct listaDoble *)malloc(sizeof(struct listaDoble));
if(num_nodos > 0)
{
result->first = (struct nodo *)malloc(sizeof(struct nodo));
result->first->prev = NULL;
struct nodo *actual = result->first;
struct nodo *prev = NULL;
struct nodo *last;
for(int i = 0; i < num_nodos; i++)
{
if(i + 1 != num_nodos)
{
actual->next = (struct nodo*)(malloc)(sizeof(struct nodo));
actual->prev = prev;
actual = actual->next;
prev = actual;
}
else
{
actual->next = NULL;
actual->prev = prev;
last = actual;
}
}
result->last = last;
result->size = num_nodos;
}
else
{
result->first = NULL;
result->last = NULL;
result->size = 0;
}
return *result;
}
Requested in the comments
struct listaDoble
{
struct nodo *first, *last;
int size;
};
now this is how i call the crearMiADN
thing
struct listaDoble dni = crearMiADN();
now the expected result would be something like this
NULL<-- [1] <-> [2] <-> [3] <-> [4] --> NULL
however this is what i'm getting
NULL<-- [] <-> [] <-> [] <-> [] --> NULL
i'm not very keen with pointer, my attempt to fixing it was literally trying to put a * somewhere and see if it works (spoiler alert, it doesn't)
so something like this
struct listaDoble dni = *crearMiADN(); //type mismatch
then i tried to fix the type mismatch my doing this
struct listaDoble crearMiADN()
//...//
return *listado;
}
which once again errors out, and now i'm pretty much stuck trying to put a * somewhere random and checking if it compiles and works
You are trying to return local variable. You should allocate that memory block and return pointers. Try again by correcting the code as follows.
struct listaDoble* crearMiADN()
{
char miDni[] = "1234";
struct listaDoble *listado = crearLista(strlen(miDni));
...
return listado;
}
struct listaDoble* crearLista(int num_nodos)
{
struct listaDoble *result = (struct listaDoble *)malloc(sizeof(struct listaDoble));
...
return result;
}