malloc() triggers breakpoint in C - c

I have this program (school exercise) that simulates a software for managing tests and exercises. Everything works fine... until it doesn't. The second time, in the menu of the program, I want to add an exercise (calling so the function called inserisciEsercizio, "addExercise" in English), the malloc (esercizioPtr newEsercizio = (esercizioPtr)malloc(sizeof (esercizio));) "triggers a breakpoint". I attach the function and where the structs are declared.
What does that mean? How can I resolve it?
Thank you.
I tried looking it up, but I couldn't find anything that could help me understand.
The variables are written in Italian (half in Italian, half in English to be honest). Hope it's not too much of a problem.
struct ListaEsercizi
{
esercizioPtr esercizio;
struct ListaEsercizi *nextListaEsercizi;
};
typedef struct ListaEsercizi listaEsercizi;
typedef listaEsercizi *listaEserciziPtr;
struct Esercizio
{
char titolo[20];
char domanda[40];
char risposte[3][50];
int difficolta;
struct Esercizio *nextEsercizio;
};
typedef struct Esercizio esercizio;
typedef esercizio *esercizioPtr;
void inserisciEsercizio(esercizioPtr *firstEsercizio, autorePtr Autore)
{
listaEserciziPtr newLista = (listaEserciziPtr)malloc(sizeof (listaEsercizi));
esercizioPtr newEsercizio = (esercizioPtr)malloc(sizeof (esercizio)); // <--- here!
//se ne stabiliscono i parametri
if (newEsercizio != NULL)
{
newEsercizio->nextEsercizio = NULL;
printf("Inserisci titolo esercizio ");
scanf_s("%s", newEsercizio->titolo, 20);
printf("Inserisci domanda esercizio: ");
scanf_s("%s", newEsercizio->domanda, 30);
printf("Inserisci difficolta esercizio: ");
scanf_s("%d", &(newEsercizio->difficolta));
for (int i = 0; i < 3; i++)
{
printf(" Scrivere la risposta:\n");
scanf_s("%s", newEsercizio->risposte[i], 100);
}
if (*firstEsercizio == NULL) //caso in cui creo il primo oggetto
{
*firstEsercizio = newEsercizio;
}
else //se non il primo lo inserisco all'interno della lista oggetti
{
newEsercizio->nextEsercizio = *firstEsercizio;
*firstEsercizio = newEsercizio;
}
//mettere malloc
if (newLista != NULL)
{
newLista->nextListaEsercizi = NULL;
newLista->esercizio = newEsercizio;
if (Autore->esercizi == NULL) //caso in cui creo il primo oggetto
{
Autore->esercizi = newLista;
}
else //se non il primo lo inserisco all'interno della lista oggetti
{
newLista->nextListaEsercizi = Autore->esercizi;
Autore->esercizi = newLista;
}
}
else
{
//nel caso malloc restituisca NULL
printf("Memoria non disponibile \n");
}
}
else
{
//nel caso malloc restituisca NULL
printf("Memoria non disponibile \n");
}
}

In you declarations you have:
char risposte[3][50];
And later in the code you have:
scanf_s("%s", newEsercizio->risposte[i], 100);
It allows a 100 chars in a 50 chars array, which probaly leads to memory corruption in the first call to inserisciEsercizio. Using sizeof instead of a constant with scanf_s is usually a good idea:
scanf_s("%s", newEsercizio->risposte[i], sizeof(newEsercizio->risposte[i]));

Related

While loop stops at two iterations and the print procedure does not work

I am trying to add books of type "llist" (the second struct) to a dynamic liste of books, each has the information part of type "infoL" (the first struct) and the nxt to point the following list node;
llist ajouterEnTete(args) allows to add a new node to the start of the liste
whereas void afficherListe(args) should print out the liste to the console.
I have two issues with this code:
(1)the while loop does not iterate as many times as i set the variable "nbrl", it always iterates twice and the process freezes.
(2)the afficherListe(ma_listeLivre) does not work unless i apply to only one node, so if i enter more than one, the process is stuck at adding a new node to the start of the liste. ( screenshot of the console is included)
#include<stdio.h>
#include <stdlib.h>
typedef struct
{
int id;
char aut[30];
} infoL;
typedef struct listeLivre listeLivre;
struct listeLivre
{
infoL info;
struct listeLivre *nxt;
};
typedef listeLivre* llist;
llist ajouterEnTete(llist teteL, infoL newInfo)
{
/* On crée un nouvel élément */
llist node = malloc(sizeof(llist));
node->info=newInfo;
node->nxt=teteL;
// element* nouvelElement = malloc(sizeof(element));
/* On assigne la valeur au nouvel élément */
//nouvelElement->val = valeur;
/* On assigne l'adresse de l'élément suivant au nouvel élément */
//nouvelElement->nxt = liste;
/* On retourne la nouvelle liste, i.e. le pointeur sur le premier élément */
return node;
}
void afficherListe(llist tetel)
{
llist tmp = NULL;
tmp= tetel;
/* Tant que l'on n'est pas au bout de la liste */
while(tmp != NULL)
{
/* On affiche */
printf("ce qui doit etre afficher the id is %d ++ the author is %s +++ \n", tmp->info.id, tmp->info.aut);
/* On avance d'une case */
tmp = tmp->nxt;
}
}
int main()
{
/* Déclarons 3 listes chaînées de façons différentes mais équivalentes */
llist ma_listeLivre = NULL;
infoL LvrAjout;
int nbrl;
int i=1;
printf("how many books ? *****\n ");
scanf("%d", &nbrl);
printf("le nbr de livre %d ***\n ", nbrl);
//for (int i=0; i<nbrl; i++)
// {
while (i<=nbrl)
{
printf("entrer le id\n ");
scanf("%d", &LvrAjout.id);
printf("entrer l auteur\n ");
fflush(stdin);
gets(LvrAjout.aut);
printf("ce que j'ai ajouté %d +++ %s ++++ \n", LvrAjout.id, LvrAjout.aut );
ma_listeLivre = ajouterEnTete(ma_listeLivre, LvrAjout);
//afficherListe(ma_listeLivre);
//printf("%d \n", ma_listeLivre);
fflush(stdout);
i=i+1;
}
afficherListe(ma_listeLivre);
// return 0;
}
In trying out your program, the main issue I found which most likely is the crux of your issue was the allocation of memory for your structure.
llist node = malloc(sizeof(llist));
As is, this bit of code is only going to allocate memory for the size of the pointer and not the size of the structure and probably give you undefined behavior. Most likely, with the definitions as noted, one would want a statement such as the following.
llist node = malloc(sizeof(struct listeLivre));
With that in mind, and in order to get the program to compile, I did just a bit of refactoring. Following is the refactored code.
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int id;
char aut[30];
} infoL;
typedef struct listeLivre listeLivre;
struct listeLivre
{
infoL info;
struct listeLivre *nxt;
};
typedef listeLivre* llist;
llist ajouterEnTete(llist teteL, infoL newInfo)
{
/* On crée un nouvel élément */
llist node = malloc(sizeof(struct listeLivre)); /* Needed to use the structure size and not the pointer */
node->info=newInfo;
node->nxt=teteL;
// element* nouvelElement = malloc(sizeof(element));
/* On assigne la valeur au nouvel élément */
//nouvelElement->val = valeur;
/* On assigne l'adresse de l'élément suivant au nouvel élément */
//nouvelElement->nxt = liste;
/* On retourne la nouvelle liste, i.e. le pointeur sur le premier élément */
return node;
}
void afficherListe(llist tetel)
{
llist tmp = NULL;
tmp = tetel;
/* Tant que l'on n'est pas au bout de la liste */
while(tmp != NULL)
{
/* On affiche */
printf("What should be displayed the id is %d ++ the author is %s +++ \n", tmp->info.id, tmp->info.aut);
/* On avance d'une case */
tmp = tmp->nxt;
}
}
int main()
{
/* Déclarons 3 listes chaînées de façons différentes mais équivalentes */
llist ma_listeLivre = NULL;
infoL LvrAjout;
int nbrl = 0;
int i = 1;
printf("How many books ? *****: ");
scanf("%d", &nbrl);
printf("The number of books %d ***\n\n", nbrl);
//for (int i=0; i<nbrl; i++)
// {
while (i<=nbrl)
{
printf("Enter the id and author: "); /* Compiler had issues with the gets function so used tweaked version of scanf */
scanf("%d %[^\n]", &LvrAjout.id, LvrAjout.aut);
printf("What I added %d +++ %s ++++ \n", LvrAjout.id, LvrAjout.aut );
ma_listeLivre = ajouterEnTete(ma_listeLivre, LvrAjout);
//afficherListe(ma_listeLivre);
//printf("%d \n", ma_listeLivre);
fflush(stdout);
i=i+1;
}
afficherListe(ma_listeLivre);
return 0;
}
This is virtually your code with the change in the memory allocation, some translation to English mainly for my benefit, and revising the input using scanf for both the ID and author (I couldn't get the "gets" function to work).
With that following is some sample terminal output.
#Vera:~/C_Programs/Console/Books/bin/Release$ ./Books
How many books ? *****: 3
The number of books 3 ***
Enter the id and author: 1 ee cummings
What I added 1 +++ ee cummings ++++
Enter the id and author: 2 John Smith
What I added 2 +++ John Smith ++++
Enter the id and author: 3 George Orwell
What I added 3 +++ George Orwell ++++
What should be displayed the id is 3 ++ the author is George Orwell +++
What should be displayed the id is 2 ++ the author is John Smith +++
What should be displayed the id is 1 ++ the author is ee cummings +++
One quirk I did notice is that listing function starts the list with the last book entry working its way back to the first book. But it does produce a valid listing.
Try out these refactored tweaks and see if it meets the spirit of your project.

Issue with function that stopped my program

I have to do create a tree to register some passengers in it (from a plane flight) and then i will search them by their first letter.
My issue is that insert and print function work very well, but the search function do well for first time but when I want to do some other thing after in the main, it doesn't run the other function or things
(I tried to ask the user a letter, then use the function on research (works well here) but then for a second time to ask an other letter to user, and it prints "first letter of the person you are looking for" but i can't write the letter and it does not launch the function after this. so it stop the program there
int i;
char c;
typedef struct Passager
{
char nom[20];
char prenom[20];
int age;
int num_siege;
} Passager;
Passager liste_passagers[30]; //30 = nombre de passagers
typedef struct Arbre
{
Passager value;
struct Arbre *fils_gauche;
struct Arbre *fils_droit;
struct Arbre *racine;
} Arbre;
Arbre *const empty = NULL;
Arbre *passengers = empty; //passengers = arbre des passagers
/*--------------------------------------------*/
void liste_lettre_nom(Arbre *tree, char a)
{
Arbre *temp;
temp = tree;
if (!temp)
{
return;
}
else
{
if (a < temp->value.nom[0])
{
liste_lettre_nom(temp->fils_gauche, a);
}
if (a > temp->value.nom[0])
{
liste_lettre_nom(temp->fils_droit, a);
}
if (a == temp->value.nom[0])
{
printf("passager : \n");
print_passager(temp->value);
liste_lettre_nom(temp->fils_gauche, a);
liste_lettre_nom(temp->fils_droit, a);
}
}
}
/*--------------------------------------------*/
int main()
{
FILE* fichier = NULL;
fichier = fopen("/Users/Patoch/Desktop/Patoch /UNI/Informatique/info sem 2/Structure de données/Labo/TP3/Passager2.txt", "r");
if (fichier == NULL)
{ //test de la bonne ouverture du fichiers
printf("Impossible d'ouvrir le fichier Passagers.docx");
exit(EXIT_FAILURE);
}
for (i=0; i<(sizeof(liste_passagers)/sizeof(liste_passagers[0])); i++)
{
fscanf(fichier, "%s %s %d %d", liste_passagers[i].nom, liste_passagers[i].prenom, &liste_passagers[i].age, &liste_passagers[i].num_siege);
}
passengers = insertion(passengers, liste_passagers[1]);
passengers = insertion(passengers, liste_passagers[2]);
passengers = insertion(passengers, liste_passagers[0]);
passengers = insertion(passengers, liste_passagers[5]);
passengers = insertion(passengers, liste_passagers[26]);
print_arbre(passengers);
printf("-----------------------------\n");
printf("1ere lettre du nom de la personne recherchée: \n");
scanf("%c", &c);
liste_lettre_nom(passengers, c);
printf("-----------------------------\n");
printf("1ere lettre du nom de la personne recherchée: \n");
scanf(" %c", &c);
liste_lettre_nom(passengers, c);
destroy(passengers);
fclose(fichier);
return 0;
}

How can I solve the segmentation fault (core dumped)?

I have this code and I don't know why after, I ask if you want to introduce another student and I say 1 or 0 the program ends and said segmentation fault (core dumped).
I ask to introduce another student in _nodo *insertaEnLista
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
struct actividades
{
char tipoDeActividad[22];
char diaDeLaSemana[12];
char horaDeIncio[8];
char horaDeFin[8];
};
struct materias
{
char nombre[30];
char profesor[30];
char tipoDeMateria[20];
struct actividades *actividad;
};
struct alumnos
{
char nombre[30];
int cedula;
int telefono;
struct materias *materia;
struct alumnos *siguiente;
};
typedef struct alumnos _nodo;
_nodo *crearLista(_nodo *apuntador);
bool listaVacia(_nodo *apuntador);
_nodo *insetarEnLista(char nombre[], long cedula, long telefono, _nodo *apuntador);
void imprimirLista (_nodo *apuntador);
_nodo *crearNodo(char nombre[], long int cedula, long int telefono);
//AQUI SE CREA LISTA Y SE PONE PARA QUE APUNTE A NULL
_nodo *crearLista(_nodo *apuntador)
{
return (apuntador = NULL);
}
//ESTA FUNCION VERIFICA SI LA LISTA ESTA VACIA
bool listaVacia(_nodo *apuntador)
{
if (apuntador == NULL)
return (true);
else
return (false);
}
//AQUI SE CREA EL NUEVO NODO DE LA LISTA
_nodo *crearNodo(char nombre[], long cedula, long telefono)
{
_nodo *registroNuevo;
registroNuevo = (_nodo *) malloc(sizeof(_nodo));
printf("\n----NUEVO ELEMENTO----\n");
printf("NOMBRE: ");
fflush(stdin);
scanf("%s",nombre);
printf("CEDULA: ");
fflush(stdin);
scanf("%ld", &cedula);
printf("TELEFONO: ");
fflush(stdin);
scanf("%ld", &telefono);
fflush(stdin);
strcpy(registroNuevo->nombre, nombre);
registroNuevo->cedula = cedula;
registroNuevo->telefono = telefono;
registroNuevo->siguiente = NULL;
return registroNuevo;
}
//AQUI SE INSERTA EL NODO EN LA LISTA LUGEO DE SER CREADO POR LA FUNCION crearNodo
_nodo *insetarEnLista(char nombre[], long cedula, long telefono, _nodo *apuntador)
{
_nodo *registroNuevo, *apuntadorAuxiliar;
char respuesta,ch;
do
{
registroNuevo=crearNodo(nombre, cedula, telefono);
if (listaVacia(apuntador)) apuntador = registroNuevo;
else
{
apuntadorAuxiliar = apuntador;
while (apuntadorAuxiliar->siguiente != NULL)
apuntadorAuxiliar = apuntadorAuxiliar->siguiente;
apuntadorAuxiliar->siguiente = registroNuevo;
}
printf("\nPARA INGRESAR A OTRO ALUMNO MARQUE... 1");
printf("\nPARA SALIR MARQUE... '0'\n");
while((ch = getchar()) != EOF && ch != '\n');
scanf("%c", &respuesta);
fflush(stdin);
printf("RESPUESTA = %c", respuesta);
}while (strcmp(&respuesta, "1")==0);
return apuntador;
}
//IMPRIMIR LOS NODOS DE LA LISTA
void imprimirLista (_nodo *apuntador)
{
_nodo *apuntadorAuxiliar;
apuntadorAuxiliar = apuntador;
if (apuntador == NULL)
printf("NO HAY ELEMENTOS EN LA LISTA \n");
else
{
while(apuntador != NULL)
{
printf(" \n------------NODO-------------- ");
printf("\nNOMBRE: %s \n\n", apuntadorAuxiliar->nombre);
printf("\n\nCEDULA: %d \n", apuntadorAuxiliar->cedula);
printf("\nTELEFONO: %d \n", apuntadorAuxiliar->telefono);
apuntadorAuxiliar = apuntadorAuxiliar->siguiente;
}
}
return;
}
int main()
{
/*printf("INTRODUZCA LOS NUMEROS DE CEDULA QUE DESEA IMPRIMIR \n");*/
_nodo *inicioLista;
int cedula;
int telefono;
char nombre[20];
inicioLista = crearLista(inicioLista);
inicioLista = insetarEnLista(nombre, cedula, telefono, inicioLista);
imprimirLista(inicioLista);
return 0;
}
How can I do to fix the problem.
You should step through the code in a debugger and look at the variables at each step to determine the line of code that is causing the issue.
Here is one issue, there may be others.
In this line
}while (strcmp(&respuesta, "1")==0);
you are using strcmp with a variable (respuesta) that contains a single character. strcmp is expecting a null terminated string (an array of characters with a zero byte at the end). As you may not have a zero byte after the variable, this may cause strcmp to read memory that it shouldn't (this is a buffer overrun)
Much simpler to just use:
}while (respuesta == '1');

strange behavior of strncmp

this code has a strange behavior in the "check_connected" procedure.
The parameter is converted to char [30] before use the strncmp function, if not, the result is "stack overflow". The problem arises in the result of the compare of two strings,
"Le solteria rige el corason.." --> this is the parameter
"La solteria rige el corazon..." --> this is stored in the list
The result is 0. I understand that the strncmp compare all the character of the strings and by common sense the result should not by zero.
#include <string.h>
#include <stdio.h>
#define LONGITUD_USUARIO 30
//estructuras de socorro
typedef struct nodo_list{
char id_usuario[LONGITUD_USUARIO];
struct nodo_list *siguiente;
} nodo;
//definiciones
#define TRUE 1
#define FALSE 0
//variables
nodo *headlist;
int size_var;
//declaracion de metodos
void initialize_list();
int add_connected(char *id_usuario);
int check_connected(char *id_usuario);
int disconnect(char *id_usuario);
int isEmpty();
int size();
//implementacion de metodos
/*
Dado un id usuario lo incorpora al principio de la lista
*/
int add_connected(char *id_usuario){
nodo nuevoNodo;
strcpy(nuevoNodo.id_usuario, id_usuario);
nuevoNodo.siguiente = headlist;
headlist = &nuevoNodo;
size_var++;
return TRUE;
}
int check_connected(char *id_usuario){
nodo *cursor = headlist;
char id_user[LONGITUD_USUARIO];
sprintf(id_user,"%s",id_usuario);
printf(" ----> %d \n",strncmp(cursor->id_usuario, id_user,LONGITUD_USUARIO));
if(!isEmpty()){
while(cursor != NULL && (strncmp(cursor->id_usuario, id_user,LONGITUD_USUARIO) != 0)){
printf(" ----> %d \n",strncmp(cursor->id_usuario, id_user,LONGITUD_USUARIO));
cursor = cursor->siguiente;
}}
return cursor != NULL ;
}
int disconnect(char *id_usuario){
nodo *cursor = headlist, *anterior = NULL;
char id_user[LONGITUD_USUARIO];
sprintf(id_user,"%s",id_usuario);
if(!isEmpty()){
while(cursor != NULL && strncmp(cursor->id_usuario, id_user, LONGITUD_USUARIO) != 0){
anterior = cursor;
cursor = cursor->siguiente;
}
if(anterior == NULL){ // es el primero
headlist = cursor->siguiente;
size_var--;
return TRUE;
}
else
if(cursor != NULL){
anterior->siguiente = cursor->siguiente;
size_var--;
return TRUE;
}
}
return FALSE;
}
void initialize_list(){
headlist = NULL;
size_var = 0;
}
int size(){
return size_var;
}
int isEmpty(){
return size() == 0;
}
void tester_list(){
initialize_list();
printf("Inicializo\n");
if(add_connected("Betina la corbina"))
printf("Agrego a Betina\n");
if(add_connected("CREO EN LA REENCARNACIÓN...(LA UÑA)"))
printf("Agrego a la uña\n");
if(add_connected("La solteria rige el corazon..."))
printf("Agrego a la solteria\n");
printf("ZISE --> %d \n",size());
if(check_connected("Le solteria rige el corason.."))
printf("Cualquiera se mando\n");
if(check_connected("La solteria rige el corazon..."))
printf("verifico correctamente solteria\n");
if(disconnect("La solteria rige el corazon..."))
printf("verifico correctamente solteria\n");
printf("ZISE --> %d \n",size());
if(add_connected("Todos los perros van al cielo..."))
printf("Agrego a perros\n");
printf("ZISE --> %d \n",size());
}
void main(){
tester_list();
}
add_connected sets the global variable headlist to point to the local, automatic variable nuevoNodo. This goes out of scope when the function returns, meaning that behaviour in check_connected and all other functions which access headlist is undefined.
I'm not sure I understand your question but would guess that you're creating a list whose elements all point to the same stack location (used for nuevoNodo in add_connected). If this is happening, note that this behaviour isn't guaranteed.
You want nodes created inside add_connected to remain valid after the function returns so need to allocate memory dynamically:
int add_connected(char *id_usuario){
nodo* nuevoNodo = malloc(sizeof(*nuevoNodo));
if (nuevoNodo == NULL) {
printf("Error - out of memory\n");
return FALSE;
}
strcpy(nuevoNodo->id_usuario, id_usuario);
nuevoNodo->siguiente = headlist;
headlist = nuevoNodo;
size_var++;
return TRUE;
}
At the end of your program, you'll now need to call a new function which calls free for each node in your list.

How to pass a linked list from a file to another in the same project?

I am doing a C project that manages the number of rooms in a building, where I can either choose to reserve or pre-reserve a room.
My problem is that I can't figure out a way of passing a linked list from a file to another.
My main.c looks like this (it's a menu):
int main()
{
printf("--------------------------------------------------------------------------------\n");
time_t t;
time(&t);
printf("Data: %s\n", ctime(&t));
printf("--------------------------------------------------------------------------------\n");
int opcao;
do{
printf("\n\tM E N U P R I N C I P A L\n");
printf("\n\n\t1 - Ver Reservas Actuais Por Ordem Cronologica");
printf("\n\n\t2 - Fazer A Sua Reserva");
printf("\n\n\t3 - Estado Da Sua Reserva");
printf("\n\n\t4 - Cancelar A Sua Reserva");
printf("\n\n\t5 - Sair");
printf("\n\n\n\t\tOpcao: ");
scanf("%d", &opcao);
printf("\n");
fflush(stdin); /*Limpa o Buffer*/
switch (opcao)
{
case 1 : Listar_Fila(FILA Fila); break;
case 2 : lista_reserva(); break;
/*case 3 : estado_reserva(); break;
case 4 : cancelar_reserva(); break;*/
case 5 : puts("Obrigado por ter preferido o nosso sistema!");break;
default : puts("OPCAO INVALIDA!!");
}
getchar(); /*Para a tela*/
}
while (opcao!=5);
}
This is how I do my linked list:
void lista_reserva()
{
FILA F;
char prim_nome_temp[100];
char ult_nome_temp[100];
int hora_inic_temp_h , hora_inic_temp_m;
int hora_fim_temp_h , hora_fim_temp_m;
int sala_temp;
inicia_fila(&F);
puts("Iniciar");
Listar_Fila(F);
printf("Inserir Primeiro Nome: ");
scanf("%s",prim_nome_temp);
printf("Inserir Ultimo Nome: ");
scanf("%s",ult_nome_temp);
printf("Indique que sala pretende reservar: ");
scanf("%d", &sala_temp);
printf("Inserir hora de inicio (HH:MM): ");
scanf("%02d:%02d",&hora_inic_temp_h, &hora_inic_temp_m);
printf("Inserir hora de fim (HH:MM): ");
scanf("%02d:%02d",&hora_fim_temp_h , &hora_fim_temp_m);
insere_fila(&F, sala_temp, hora_inic_temp_h , hora_inic_temp_m , hora_fim_temp_h , hora_fim_temp_m , prim_nome_temp , ult_nome_temp);
Listar_Fila(F);
}
/* Iniciar uma fila */
void inicia_fila(FILA *Fila)
{
*Fila = NULL;
}
/*Inserir na Fila */
void insere_fila(FILA *Fila , int sala , int hora_inic_h , int hora_inic_m , int hora_fim_h , int hora_fim_m , char *prim_nome , char *ult_nome)
{
if (*Fila == NULL)
{
*Fila = (FILA) malloc(sizeof(reservas));
if (*Fila == NULL)
return;
((*Fila)-> sala = sala);
((*Fila)-> hora_inic_h = hora_inic_h);
((*Fila)-> hora_inic_m = hora_inic_m);
((*Fila)-> hora_fim_h = hora_fim_h);
((*Fila)-> hora_fim_m = hora_fim_m);
strcpy((*Fila)-> prim_nome , prim_nome);
strcpy((*Fila)-> ult_nome , ult_nome);
(**Fila).proximo = NULL;
}
else
insere_fila(&(**Fila).proximo , sala , hora_inic_h , hora_inic_m , hora_fim_h , hora_fim_m , prim_nome , ult_nome );
}
And this is how I print it:
void Listar_Fila(FILA Fila)
{
if (Fila == NULL)
return; /*Não existem elementos*/
printf("Sala %d das %d:%d as %d:%d, reservado por %s %s\n\n", Fila -> sala ,Fila ->hora_inic_h , Fila -> hora_inic_m ,Fila -> hora_fim_h , Fila -> hora_fim_m , Fila -> prim_nome , Fila -> ult_nome);
Listar_Fila(Fila -> proximo);
}
I am sorry that my project is not in English and I know it has many beginner mistakes, as I had never worked with C before and I am doing this just has a challenge.
Please, help me improve with any constructive criticism.
Thanks
The standard way to do this is do create the linked list as an "ADT", an abstact data type. It consists of a h-file with all the interface functions that main should call, in order to use the linked list. The functions are defined in the corresponding c-file. Simplified example:
// list.h
typedef struct
{
// whatever data you want each node to contain
} node_t;
typedef struct
{
node_t* head;
node_t* tail; // optional
int size; // optional
} list_t
void list_init (list_t* list);
void list_add (list_t* list, const node_t* node);
void list_remove (list* list, node_t* node);
void list_destroy (list_t* list);
And then in list.c, the functions are defined.

Resources