Chained list returning empty outside function

Asked

Viewed 43 times

0

I’m trying to read data from a file .obj and insert into a chained list, I have a function to read and within it I call the insert function. When I call the function of printing the list inside the function read after having entered all values works normally, but when I call in the most after the call of the function reading 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 file data 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 printing 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 call in main, don’t print anything, as if the list is empty. For example:

main(){
  LerArquivo(lv,lf);
  ImprimirListaVertice(lv);
}

1 answer

0

The problem is in these two instructions, 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 the main, and so change them within this function does not alter those in the main.

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

Then your job 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 the main also had to change to:

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

Note that only the function has been changed LerArquivo because it is the only one that tries to change the pointers that had in the main. To ImprimirListaVertice only use the pointer.

Related reading that I recommend

Browser other questions tagged

You are not signed in. Login or sign up in order to post.