在以下伪代码中:
#include<stdio.h>
typedef struct _apple
{
int a;
char b;
float c;
} apple;
typedef struct _orange
{
int a;
int b;
} orange;
typedef struct _grape
{
int a;
} grape;
void main()
{
apple a1;
orange o1;
a1.a =1;
a1.b =2;
a1.c =3;
o1.a =4;
void * fruit[] = {&a1, &o1};
grape *app = (grape*)fruit[0];
printf ("\nRead: %d ", app->a);
app = (grape*)fruit[1];
printf ("\nRead: %d ", app->a);
}葡萄结构是苹果和橘子的一个子集,因为它包含的元素与苹果和橘子的顺序相同。这个程序将预期的输出作为1和4。但是这种方法是否有可能在不同的编译器或任何其他特定环境的更改中失败?
发布于 2014-01-10 12:18:39
您可以使用union处理所有类型:
typedef struct {
/* Common elements */
int a;
/* Type specific */
union {
struct {
char b;
float c;
} apple;
struct {
int b;
} orange;
} special;
} fruit;
fruit or;
or.a = 1;
or.special.orange.b = 2;
fruit * f = ∨或者模仿对象继承:
/* Common elements (base class) */
typedef struct {
int a;
} fruit;
/* Extended types */
typedef struct {
fruit parent; /* Must be first */
} grape;
typedef struct {
fruit parent; /* Must be first */
int b;
} orange;
orange or;
or.parent.a = 1;
or.b = 2;
fruit * f1 = (fruit*)∨
fruit * f2 = &or.parent; /* alternate type safe way */或者使用C++获得适当的继承。
发布于 2014-01-10 12:01:50
如果您知道您的指针指向指针没有真正指示的东西,则应该进行任何转换。但是,当您假设编译器已经以特定的方式编译了一些东西时,就不应该进行强制转换。
当更改任何结构元素时,您的方法将失败。它违反了可维护性的要求。您的方法在任何新的编译器变体上都可能失败。
https://stackoverflow.com/questions/21043589
复制相似问题