2
I defined two structures to represent a straight line. I need to open a file that contains the values of a line by line, put the values in a chained list. This I was able to do.
#include<stdio.h>
typedef struct{
int x,y;
}ponto;
typedef struct a{
ponto p1,p2;
struct a *prox;
}no;
no *aloca_no(){
no *a;
if(!(a=(no*)malloc(sizeof(no))))
exit(1);
a->prox = NULL;
return a;
}
void incluir_no(no **lista, no*novo){
if(*lista == NULL){
*lista = novo;
}
else{
no *aux = *lista;
novo->prox = NULL;
while(aux->prox)
aux = aux->prox;
aux->prox = novo;
}
}
void lerDados(no **dadosEntrada, char *local){
FILE *arquivo;
no *acc;
if(!(arquivo = fopen(local,"r")))
exit(1);
else{
printf("Foi\n");
while(!(feof(arquivo))){
acc = aloca_no();
fscanf(arquivo,"%d %d %d %d\n", &(acc->p1.x), &(acc->p1.y), &(acc->p2.x), &(acc->p2.y));
incluir_no(dadosEntrada, acc);
}
fclose(arquivo);
}
}
The function lerDados
works perfectly, she calls incluir_no
to insert at the end of the list. For each line of the file read, the function lerDados
creates a knot and put it on the list.
After reading the data, if I perform another function to print the read data the code works.
void imprime_lista(no *imprime, char *nome){
no *aux = imprime;
while(aux){
printf("-----------------------%s-----------------------\n%d %d || %d %d\n", nome,aux->p1.x, aux->p1.y, aux->p2.x, aux->p2.y);
aux = aux->prox;
}
}
However, if I try to use another function, which does NOTHING only receives 2 pointers as parameter, occore the fault error in segmentation....
void retas_verticais(no *dadosEntrada, no *verticais){
printf("uéé");
}
void main(){
no *dadosEntrada, *verticais, *horizontais, *inclinadas;
char local[50]="/home/lua/Workspace/Algoritmos2/dados.txt";
lerDados(&dadosEntrada, local);
imprime_lista(dadosEntrada, "Dados Brutos");
retas_verticais(dadosEntrada, verticais);
}
The data can be obtained from here -> http://www.edison.unifei.edu.br/publico/COM112/2016-1/COM112_DADOS.txt
Its function include in this forgetting to put NULL in the empty list Prox. (*list) ->Prox = NULL;
– Felipe
I forgot to put the aloca_no function, it leaves the new node with the field Prox NULL..
– Luã Faria
The level of eotimization (O2, O3, etc.) should not change the behavior of your program. If you went down with O3 it might just be luck... I recommend you learn how to use a debugger like gdb or ddd. It is very difficult to find the cause of a failure if targeting only with printf.
– hugomg
Bugs in compilers exist, but usually in obscure corners of the language. Your problem certainly lies in your code.
– Pablo Almeida