Is it possible to change the definition of structs

2019-06-14 21:28发布

问题:

I don't know why you would ever want to do this, but I was curious if anyone knew the answer. Is it possible at run time to use one struct definition for a while, and then later change that definition?

i.e.

typedef struct
{
    int a;
    int b;
}my_struct;

and later on...

typedef struct
{
    int a;
    int b;
    int c;
}my_struct;

回答1:

No, you can't change the definition of a given type, but there's nothing wrong with casting it to a totally different type, assuming the underlying data is similarly laid out and otherwise compatible.

For example, consider:

struct s_xyzzy {
    int a;
    int b;
};

struct s_plugh {
    int a;
    char b0;
    char b1;
    char b2;
    char b3;
};

struct s_xyzzy *xyzzy = malloc (sizeof (*xyzzy));
((struct s_plugh *)xyzzy)->b0 = 'x';

By casting xyzzy to a different but compatible type, you can access the fields in a different way.

Keep in mind that compatibility is important and you have to know that the underlying memory will be correctly aligned between the two structures.

You can also do it by placing both structures into a union, using overlapped memory.



回答2:

If you're talking about runtime polymorphism, then it can be made to work, but you have to know what you're doing. Read ooc.pdf by Axel Schreiner.



标签: c struct runtime