Type of polymorphism in C

I am writing a C program in which I define two types:

typedef struct {

    uint8_t array[32];
    /* struct A members */
    ...

} A;

typedef struct {

    uint8_t array[32];
    /* struct B members, different from A */
    ...

} B;

Now I would like to build a data structure that is capable of managing both types without having to write one for type A and one for type B, assuming that both of them have uint8_t [32] as their first member.

I read how you can implement some kind of polymorphism in C, and I also read here that the order of the structure members is guaranteed to be stored by the compiler, as written by the programmer.

I came up with the following idea: what if I define the following structure:

typedef struct {
    uint8_t array[32];
} Element;

and define a data structure that only applies to data of type Element? It would be safe to do something like:

void f(Element * e){
    int i;
    for(i = 0; i < 32; i++) do_something(e->array[i]);
}

...

A a;
B b;
...
f(((Element *)&a));
...
f(((Element *)&b));

At first glance it looks unclean, but I was wondering if there were any guarantees that it would not break?

+4
3

array , . Element. void.

typedef struct {
    char array[32];
} A;

typedef struct {
    void* elements;
    size_t elementSize;
    size_t num;
} Vector;

char* getArrayPtr(Vector* v, int i) {
    return (char*)(v->elements) + v->elementSize*i;
}

int main()
{
    A* pa = malloc(10*sizeof(A));
    pa[3].array[0] = 's';
    Vector v;
    v.elements = pa;
    v.num = 10;
    v.elementSize = sizeof(A);
    printf("%s\n", getArrayPtr(&v, 3));
}
+1

, void f(uint8_t array[32]){ int i; for(i = 0; i < 32; i++) do_something(array[i]); }

f(a.array) f(b.array)

, kepp a b - , , .

0

, , , . A element, , , .

A, element, A - . element A, A undefined. .

( ), gcc struct ( ), C. , () (suncc), . , .

0

Source: https://habr.com/ru/post/1534918/


All Articles