In this program, I'm trying to implement a linked list using an array. I initialised the elements of the array tabList to -1 so that I can consider every element of the array whose value is -1 as an empty box that i can use to store a new element in the list.
I am getting segmentation error when trying to run this program. Can you explain please what is the error in my code
I tried to debug my code, It says that there's an error in line 75 : while(list.tabList[i].valeurElem != -1)
Here is my code :
typedef struct elementList
{
int valeurElem;
int indexSuivant;
int indexElem;
} elementList;
typedef struct list{
elementList tabList[tailleMax];
int debut;
int fin;
} listT;
// To initialize the list
void initListT(listT list)
{
for(int i = 0; i < tailleMax; i++)
{
list.tabList[i].valeurElem = -1;
list.tabList[i].indexSuivant = -1;
list.tabList[i].indexElem = -1;
}
}
// To create a new linked list
listT creerListeT()
{
listT alist;
initListT(alist);
alist.debut = 0;
alist.fin = 0;
return alist;
}
// To test if the list is empty
bool estVideListT(listT list)
{
return list.tabList[ 0 ].valeurElem == -1 ;
}
// Function To insert in the head of the linked list
listT insererTeteListT(listT list, int elemInserer)
{
if( estVideListT(list) )
{
int a = list.debut;
list.tabList[ a ].valeurElem = elemInserer;
list.tabList[ a ].indexSuivant = list.debut + 1;
list.tabList[ a ].indexElem = list.debut;
return list;
}
else
{
int i = 0;
while(list.tabList[i].valeurElem != -1)
{
i++;
}
list.tabList[ i ].valeurElem = elemInserer;
list.tabList[ i ].indexSuivant = list.debut;
list.debut = i;
return list;
}
}
void printList(listT list)
{
if( estVideListT(list) ) // testing if the array is empty
{
printf("The array is empty\n");
}
else
{
int i = list.debut;
while( list.tabList[i].indexSuivant != -1 )
{
printf("Element with index %d is : %d \n", i, list.tabList[i].valeurElem);
i++;
}
printf("Element with index %d (Last element) is : %d \n", i, list.tabList[i].valeurElem);
}
}
int main()
{
// Creating the list
listT myList = creerListeT();
// Insertion of the elements in the list (each element in the head of the list)
insererTeteListT(myList, 5);
insererTeteListT(myList, 3);
insererTeteListT(myList, 2);
insererTeteListT(myList, 4);
insererTeteListT(myList, 7);
// Printing the list
printList(myList);
return 0;
}