Search code examples
ctypesansi-c

Get the same field from different structures using the same function in C


I want to have two structures in C, for example:

A:

typedef struct a
{
     char *text;
     int something;
}A;

and B:

typedef struct b
{
     char *text;
     float something_else;
}B;

Now, as far as I know, it is not possible to have a function which takes a void * parameter to get the text element from both structures. Am I wrong, is this possible in standard C?


Solution

  • Yes you can, using casting and the fact that the text element is the first element of both structures:

    void f(void *t)
    {
        printf("%s\n", *((char **)t));
    }
    
    int main()
    {
         struct a AA = {"hello",3};
         struct b BB = {"world",4.0};
    
         f(&AA);
         f(&BB);
         return 0;
     }
    

    Note: Passing the address of the struct means it points to the address of text. This must then still be dereferenced one more time to get at the adress of the text itself, which is then passed to printf.

    Edit: a cast to (void *) in the calls to f are not necessary (casts removed).