Hello Guys,
so I have this question today. let's say I defined a structure like this :

   struct List{
    char *co;
    char *di;
    List* next;
     };

I wanted to define a function with a pointer to a list of elements of this structure as a parameter. In the body of the function the list items should be deleted, but not the C strings ,to which the two pointers apply. Any ideas how to define this function.

Thanks a lot!

Assuming that the strings are dynamically allocated (with operator new or the C-style malloc/calloc functions) then they will remain around after the list pointer is deleted. More code would be helpful to enable us to better advise you.

commented: It's a type of linked lists in C++ +0

It is my assignment for Uni, in which I have to write a program which reads a csv file after user inputs a code or a name of disease (something like WHO ICD codes). First instruction is to Define a structure to build a list (that is, for two pointers to C strings char * , not C ++ data type string ) and contains a pointer to the next element of the list and then Define a function with a pointer to a list of elements of this structure as a parameter. In the body of the function list items should be deleted, but not the C strings. so I defined the structure but I don't know how to define the function

struct liste{
    char *co;
    char *di;
    liste* next;
};

Am I clear enough? :(

Ok. Do you understand recursive functions? The simplest way is recursive, deleting the items from the tail of the list, otherwise you will have to keep storing the address of the next item, until the 'next' item is null. I'm not going to write your code for you since this is a class assignment. You write what you think is appropriate code, and we will help you debug it.

The code i tried are this ones

void l_del(liste*& list){
    if(list == NULL)
        return;
     func3(list->next);
     delete(list);
     list = NULL;
}

or//
void l_del(liste* next)
{

    if (next == NULL)
        return;
    else {
        func3(next->next);
        delete next;
    }
}

any correction is welocme and plus anything with loop to save memory :) Thanks a lot

There are two main ways to delete a list that I know. You can use recursion or you can iterate.

// recursion
void delete(listNode node)
{
    if (node.next != nullptr)
        delete(node.next);
    delete node;
}

// iteration
void delete(listNode node)
{
    listNode temp;
    while (node != nullptr)
    {
        temp = node.next;
        delete node;
        node = temp;
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.