C two functions in one with casts

Posted by Favolas on Stack Overflow See other posts from Stack Overflow or by Favolas
Published on 2012-06-06T16:15:52Z Indexed on 2012/06/06 16:40 UTC
Read the original article Hit count: 233

Filed under:
|

I have two functions that do the exact same thing but in two different types of struct and this two types of struct are very similar.

Imagine I have this two structs.

typedef struct nodeOne{
    Date *date;
    struct nodeOne *next;
    struct nodeOne *prev;
}NodeOne;

typedef struct nodeTwo{
    Date *date;
    struct nodeTwo *next;
    struct nodeTwo *prev;
}NodeTwo;

Since my function to destroy each of the list is almost the same (Just the type of the arguments are different) I would like to make just one function to make the two thins.

I have this two functions

void destroyListOne(NodeOne **head, NodeOne **tail){
    NodeOne *aux;

    while (*head != NULL){
        aux = *head;
        *head = (*head)->next;
        free(aux);
    }
    *tail = NULL;
}

and this one:

void destroyListTwo(NodeTwo **head, NodeTwo **tail){
    NodeTwo *aux;

    while (*head != NULL){
        aux = *head;
        *head = (*head)->next;
        free(aux);
    }
    *tail = NULL;
}

Since they are very similar I thought making something like this:

void destroyList(void **ini, void **end, int listType){

    if (listType == 0) {
        NodeOne *aux;
        NodeOne head = (NodeOne) ini;
        NodeOne tail = (NodeOne) ed;

    }
    else {
        NodeTwo *aux;
        NodeTwo head = (NodeTwo) ini;
        NodeTwo tail = (NodeTwo) ed;
    }

    while (*head != NULL){
        aux = *head;
        *head = (*head)->next;
        free(aux);
    }
    *tail = NULL;
}

As you may now this is not working but I want to know if this is possible to achieve.

I must maintain both of the structs as they are.

© Stack Overflow or respective owner

Related posts about c

    Related posts about casting