C Programming.. Typecasting of structure pointers..

Hi,
I need to pass a typecasted structure pointer of one structure to another structure pointer..
The parameters of both structures are different say if first structure has int, char datatypes and second structure has float, double,char..
Please help.. I need to get the values of one structure and pass them to another structure..
Its pretty confusing me..:eek:

It sounds like you need a single structure containing a union rather than multiple structures. If you can show us details about what structures you have and what you're trying to get out of them, we might be able to help more.

Yes, what you usually do is something like this:

#include <stdio.h>

typedef struct type_float {
        int type;
        float payload;
} type_float;

typedef struct type_string {
        int type;
        char payload[64];
} type_string;

typedef union alltypes {
        /* An enum is like an integer, plus a bunch of #define's.
            TYPE_FLOAT becomes 0, TYPE_STRING becomes 1, etc, etc. */
        enum { TYPE_FLOAT, TYPE_STRING } type;
        type_float t_float;
        type_string t_string;
} alltypes;

int dosomething(alltypes *a)
{
        switch(a->type)
        {
        case TYPE_FLOAT:
                printf("TYPE_FLOAT:  %f\n", a->t_float.payload);
                break;
        case TYPE_STRING:
                printf("TYPE_STRING:  %s\n", a->t_string.payload);
                break;
        default:
                printf("Wrong type '%d'\n", a->type);
                return(-1);
                break;
        }

        return(0);
}

int main(int argc, char *argv[])
{
        type_float tf={TYPE_FLOAT, 3.14159 };
        type_string ts={TYPE_STRING, "HEY GUYS"};
        dosomething((alltypes *)&tf);
        dosomething((alltypes *)&ts);
        return(0);
}

Note that a union actually stores all elements in the same place, so its members t_float, t_string and type actually start at the same address. They all share their type variable in common. (Wherever the held-in-common variable is used, I highlight in red.) So you can pass different types of structures, and have the first value define which type it gets used as, without lots of different kinds of messy typecasts.

1 Like

Thanks a lot.. This was the exact thing i was searching to do.. It really worked.. :smiley: