Hello guys,
been struggling with implementing a linked list.
I'm using this function AddToList to add elements. I'm clearly doing something wrong because no new element is added. Although when Im using a breakpoint inside the function i see that it seems right.

/* Main.cpp */
#include "LankadLista.h"
#include <stdio.h>
#include <conio.h>

int main(void){
	LankadLista *firstnode = NULL;

	AddToList(firstnode, "Firstnode");
	AddToList(firstnode, "Secondnode");

	while(firstnode != NULL){
		printf("Node: %s", firstnode->name);
	}
	_getch();
}
/* LankadLista.cpp */
#include "LankadLista.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void AddToList(LankadLista *lista, char name[]){
	LankadLista *newnode;
	newnode = (LankadLista*)malloc(sizeof(LankadLista));
	newnode->next = NULL;
	strcpy(newnode->name,name);

	if(lista == NULL){	// Empty List
		lista = newnode;
	}
	else{ 
		LankadLista *thisnode = lista;
		while(thisnode != NULL){
			thisnode = thisnode->next;
		}
		thisnode->next = newnode;
	}
}
/* LankadLista.h */
#ifndef LANKADLISTA_H
#define LANKADLISTA_H

#define MAX_LENGTH 30

struct LankadLista{
	char name[MAX_LENGTH];
	LankadLista *next;
};

void AddToList(LankadLista *lista, char name[]);

typedef struct LankadLista LankadLista;

#endif

firstnode never changes. AddToList is passed the _value_ of firstnode (which is NULL), and operates on the local variable. Upon return, firstnode remains NULL.

You have to either pass an address of firstnode,

void AddToList(LankadLista ** listaptr, char name[])
{
    ...
    *listaptr = newnode;
    ...
}

main()
{
    ...
    AddToList(&firstnode, ...);
    ...
}

or return the modified local:

LankadLista * AddToList(LankadLista * lista, char name[])
{
    ...
    return lista;
}

main()
{
    ...
    firstnode = AddToList(firsnode, ...);
    ...
}
void AddToList(LankadLista ** listaptr, char name[])
{
    ...
    *listaptr = newnode;
    ...
}

main()
{
    ...
    AddToList(&firstnode, ...);
    ...
}

Thanks mate, got it working!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.