Question

I want to make a method that deletes elements called "archivo" from a list if cantLineas=0, the method deletes everything just right but I can't make it to put the pointer to NULL when the list has been deleted completely. Here is the code I've written:

struct archivo
{
    char * nombre;
    int cantLineas;
    archivo * sig;
};


void borrarArchivos(archivo * listaArchivos){
    archivo * ant=NULL;
    while(listaArchivos!=NULL){
        if(listaArchivos->cantLineas==0){
            if(ant!=NULL){
                ant->sig=listaArchivos->sig;
                delete listaArchivos;
                listaArchivos=ant->sig;
            }else{
                ant=listaArchivos;
                listaArchivos=listaArchivos->sig;
                delete ant;
                ant=NULL;
            } 
            if(ant==NULL && listaArchivos==NULL){
                listaArchivos=NULL;
            }
        }else{
            ant=listaArchivos;
            listaArchivos=listaArchivos->sig;
        }

    }
}
Was it helpful?

Solution

You are passing the pointer listArchivos by value, you have to pass it by reference. In order to achieve this you have to pass a double pointer or a reference to a pointer (see code below):

Double Pointer:

void borrarArchivos(archivo **listaArchivos) {
    archivo *ant=NULL;
    while(*listaArchivos!=NULL){
        if((*listaArchivos)->cantLineas==0){
            if(ant!=NULL){
                ant->sig=(*listaArchivos)->sig;
                delete *listaArchivos;
                *listaArchivos=ant->sig;
            }else{
                ant=*listaArchivos;
                *listaArchivos=(*listaArchivos)->sig;
                delete ant;
                ant=NULL;
            } 
            if(ant==NULL && *listaArchivos==NULL){
                *listaArchivos=NULL;
            }
        }else{
            ant=*listaArchivos;
            *listaArchivos=(*listaArchivos)->sig;
        }

    }
}

Reference to a Pointer:

void borrarArchivos(archivo *&listaArchivos){
    archivo * ant=NULL;
    while(listaArchivos!=NULL){
        if(listaArchivos->cantLineas==0){
            if(ant!=NULL){
                ant->sig=listaArchivos->sig;
                delete listaArchivos;
                listaArchivos=ant->sig;
            }else{
                ant=listaArchivos;
                listaArchivos=listaArchivos->sig;
                delete ant;
                ant=NULL;
            } 
            if(ant==NULL && listaArchivos==NULL){
                listaArchivos=NULL;
            }
        }else{
            ant=listaArchivos;
            listaArchivos=listaArchivos->sig;
        }

    }
}

Better yet, use the power of C++ STL and use smart pointers instead of raw C pointer and take advantage of STL containers like std::vector to manage and store your objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top