简体   繁体   中英

Array of pointers of different structs in C

Is it possible to have an array of pointers of different structs that have same size ? If yes would it possible to access from the array the structs variables or members ? Can you give some examples ?

Thanks

Strictly speaking you can't. But you can keep pointers to base structure! When I was need "OOP" at C, i used this approach (as example):

// http://ideone.com/FhSULX

#include <stdio.h>


struct BaseFigure
{
    int type;
    const char * name;
};

struct RectangleFigure
{
    struct BaseFigure base; // must be first field!
    int width, height;
};

struct CircleFigure
{
    struct BaseFigure base; // must be first field!
    float radius;
};

enum {FIGURE_RECTANGLE, FIGURE_CIRCLE};

int main()
{
    enum {FIGURE_COUNT = 2};

    struct BaseFigure *arrayOfFigures[FIGURE_COUNT];
    struct RectangleFigure rectangle;
    struct CircleFigure circle;
    int i;

    rectangle.base.name = "rectangle";
    rectangle.base.type = FIGURE_RECTANGLE;
    rectangle.width = 10;
    rectangle.height = 20;

    circle.base.name = "circle";
    circle.base.type = FIGURE_CIRCLE;
    circle.radius = 3.5f;

    arrayOfFigures[0] = (struct BaseFigure*)&rectangle;
    arrayOfFigures[1] = (struct BaseFigure*)&circle;

    for (i = 0; i < FIGURE_COUNT; i++)
    {
        struct BaseFigure * const baseFigure = arrayOfFigures[i];
        printf("Figure type: %d, name: %s\n", baseFigure->type, baseFigure->name);
        switch (baseFigure->type)
        {
            case FIGURE_RECTANGLE:
            {
                struct RectangleFigure * const figure = (struct RectangleFigure*)baseFigure;
                printf("%s: width: %d, height: %d\n", figure->base.name,
                    figure->width, figure->height);
            }
            break;

            case FIGURE_CIRCLE:
            {
                struct CircleFigure * const figure = (struct CircleFigure*)baseFigure;
                printf("%s: radius: %f\n", figure->base.name,
                    figure->radius);
            }
            break;

            default:
                printf("Error: unknown figure with type '%d'!\n", baseFigure->type);
        }
    }

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM