Search code examples
cstructunions

Finding the union type when it has been passed to a function


I am writing a generic function to create a linked list for structs. Where I fall apart is in looping through the list to find where the new node should go, as I'm unsure how to determine which struct type is being used from within the function.

Am I able to use some if to determine the struct type?

Like

if(ID[0]==?? given that the IDs are common to both structs, but the first char will determine struct type. I am thinking there must be another way to determine the type using the type being passed to the function.

Sorry if this seems basic and I've overlooked something obvious. Any thoughts would be appreciated.

typedef struct category* CategoryTypePtr;
typedef struct item* ItemTypePtr;

/*these structs have more members, but not relevant for this*/
typedef struct item
{
    char itemID[ID_LEN + 1];
    ItemTypePtr nextItem;
} ItemType;

typedef struct category
{
    char categoryID[ID_LEN + 1];
    CategoryTypePtr nextCategory;
    ItemTypePtr headItem;
    unsigned numItems;
} CategoryType;

typedef union types{
    CategoryType cat;
    ItemType item;
} Types;

int addNode(Types *type, char *str)
{

    Types *new=NULL;
    Types *current=NULL;
    Types *prev = NULL;
    Types *head=NULL;
    char *ID;
    const char* s ="|";


    if((new=malloc(sizeof(Types)))== NULL)
    {
        fprintf(stderr,"Memory Allocation failure!!\n");
        return false;
    }

    /*get ID from first str token this is uniform to both*/
    ID=strtok(str,s);

    current = head;
    /* Search to find where in insert new list node*/
    /*WHERE <XXXX> needs to be replace by cat or item, depending on which type it is*/
    while (current != NULL && strcmp(current-><XXXX>->ID, ID)/*<<<---this is where I fall down
    the XXXX represents cat or item*/
    {
        prev = current;
        current = current->next;
    }

    /**
    code to populate struct
    a function that would be called
    depending on Types type
    */

    if (prev == NULL)
    {
        head = new;
    }
    else
    {
        prev->next = new;
    }

    return true;
}

Solution

  • Unlike some other languages, C doesn't have a built-in way to identify object types at runtime. Your method of putting an identifying character at the start of the structure is as good as any other.