Chained list returning empty out of function

0

I'm trying to read data from a .obj file and insert it into a linked list, I have a function to read and inside it I call the insert function. When I call the function to print the list inside the read function after having entered all the values it works normally, but when I call in the more after the call of the function that reads the data it is getting empty.

Definition of struct .

typedef struct listaVertice{
   int id;
   float x,y,z;
   struct listaVertice *prox;
}ListaVertice;

Function that reads the data from the file and calls the insert function in the list

void LerArquivo(ListaVertice *lv, ListaFace *lf){
FILE *fp;
float x,y,z;
int f1,f2,f3,f4;
int idVertice = 1;
char operacao;

fp = fopen("cubo.obj","r");
if(!fp)
{
    printf("\nErro ao abrir o arquivo!");
    exit(1);
}

while(fscanf(fp,"%c",&operacao)!= EOF){

    if(operacao == 'v'){
        fscanf(fp,"%f" "%f" "%f",&x,&y,&z);
        //chamada da função de inserir na lista
        lv = InserirVertice(lv,x,y,z,idVertice);
        idVertice++;
    }else if(operacao == 'f'){
        fscanf(fp,"%d" "%d" "%d %d",&f1,&f2,&f3,&f4);
        lf = InserirFace(lf,f1,f2,f3,f4);
    }
}
 //Seu realizar a chamada da função que imprime neste ponto a lista é impressa corretamente
}

Function that prints the list

void ImprimirListaVertice(ListaVertice *lv){
ListaVertice *aux;
   while(aux !=NULL){
    printf("v(%d): %f %f %f\n",aux->id,aux->x,aux->y,aux->z);
    aux = aux->prox;
   }
}

If I make the call in main, it does not print anything, as if the list was empty. For example:

main(){
  LerArquivo(lv,lf);
  ImprimirListaVertice(lv);
}
    
asked by anonymous 15.09.2017 / 02:27

1 answer

0

The problem is in these two statements, within the function LerArquivo :

void LerArquivo(ListaVertice *lv, ListaFace *lf){
    ...
    lv = InserirVertice(lv,x,y,z,idVertice);
    ...
    lf = InserirFace(lf,f1,f2,f3,f4);

The parameters lv and lf are actually copies of those are in main , and therefore change them within this function does not change those that are in main .

The solution is to pass the address of the pointers as parameter so that the function can go there and change its values.

Then your function would look like this:

void LerArquivo(ListaVertice **lv, ListaFace **lf){ //agora duplo ponteiro nos 2
    ...
    *lv = InserirVertice(lv,x,y,z,idVertice); //agora com *
    ...
    *lf = InserirFace(lf,f1,f2,f3,f4); //agora com *

And main also had to be changed to:

main(){
  LerArquivo(&lv,&lf); //agora com & para passar o endereço
  ImprimirListaVertice(lv);
}

Note that only the LerArquivo function has been changed since it is the only one that attempts to change the pointers it had in main . The ImprimirListaVertice only uses the pointer.

Related reading that I recommend

    
15.09.2017 / 04:02