1
I need to create a road map, where each path points to another and so on. I’m using pointer pointer to a list, so I can build something similar to an adjacency list, but at the time of entering the paths, something goes wrong in the second path and the program stops without at least reporting an error.
game. c
#include <stdio.h>
#include <stdlib.h>
#include "Dlist.h"
#define TAMMAX 4
Dlist** buildMap();
int main(){
Dlist **MAP = buildMap();
return 0;
}
Dlist** buildMap(){
Dlist **ROAD = malloc(TAMMAX*sizeof(Dlist*));
int i; char op;
for(i=0; i<TAMMAX; ++i){ //erro está aqui quando i>0
ROAD[i] = makeDlist();
printf("Construa o caminho %d. Digite 0 para sair!\n", i+1);
while(op = getchar(), op!='0'){
fflush(stdin);
insertDlist(ROAD[i], op);
}
printDlist(ROAD[i]);
}
return ROAD;
}
Dlist. h
#ifndef DLIST_H
#define DLIST_H
#include <stdbool.h>
typedef struct cell{
char data;
struct cell *next;
} CELL;
typedef struct Dlist{
int size;
CELL *head, *tail;
} Dlist;
Dlist* makeDlist();
void destroyDlist(Dlist* Dlist);
bool insertDlist(Dlist* Dlist, char DATA);
CELL* removeDlist(Dlist* list, int pos);
void printDlist(Dlist* Dlist);
#endif
Dlist. c
#include <stdio.h>
#include <stdlib.h>
#include "Dlist.h"
Dlist* makeDlist(){
Dlist* Dlist = malloc(sizeof(Dlist));
Dlist->size = 0;
Dlist->head = NULL;
Dlist->tail = NULL;
return Dlist;
}
void destroyDlist(Dlist* Dlist){
if(Dlist == NULL){
puts("LIST ALREADY DESTROYED!");
return;
}
CELL *AUX = Dlist->head, *BYE;
int i;
for(i=0; i<Dlist->size; ++i){
BYE = AUX;
AUX = AUX->next;
free(BYE);
}
free(Dlist);
return;
}
bool insertDlist(Dlist* Dlist, char DATA){
if(Dlist == NULL){
printf("INVALID LIST!");
return false;
}
CELL* NODE = (CELL*)malloc(sizeof(CELL));
if(!Dlist->size){
Dlist->head = NODE;
Dlist->tail = NODE;
NODE->data = DATA;
Dlist->size++;
return true;
}
Dlist->tail->next = NODE;
Dlist->tail = NODE;
NODE->data = DATA;
NODE->next = NULL;
Dlist->size++;
return true;
}
CELL* removeDlist(Dlist* Dlist, int pos){
if(!Dlist->size){
puts("EMPTY LIST!");
return NULL;
}
CELL *REMOVED = malloc(sizeof(CELL));
CELL *PREV, *CURRENT = Dlist->head;
int i;
for(i=0;i<pos-1;++i){
PREV = CURRENT;
CURRENT = CURRENT->next;
}
if(CURRENT == Dlist->head)
Dlist->head = CURRENT->next;
else
PREV->next = CURRENT->next;
REMOVED->data = CURRENT->data;
free(CURRENT);
Dlist->size--;
return REMOVED;
}
void printDlist(Dlist* Dlist){
CELL* AUX;
int i;
for(AUX=Dlist->head, i=1; AUX != NULL; AUX=AUX->next, i++){
printf("%c->", AUX->data);
}
puts("END");
}
your program is well organized, but just by visual inspection I think it will be difficult to find the error, because working with lists and pointers is notoriously prone to errors...I suggest you run in debug mode and follow step by step the execution of the program
– zentrunix