1. 例子
#include
#include
#include
typedef struct A
{
int a;
int b;
int data[0];
}A_t;
struct B : public A_t
{
int c;
int d;
};
int mytest(int aaa, int bbb)
{
struct A *aa = ( A_t *)malloc(sizeof(A_t) + sizeof(int)*bbb);
aa->a = aaa;
aa->b = bbb;
// memset(aa->data, 1, aa->b);
struct B *bb = (struct B *)malloc(sizeof(struct B));
bb->c = 3;
bb->d = 4;
aa = (struct A *)bb; //关键地方在这里
struct B *cc = (struct B *)aa;
printf("aa->a=%d\n",aa->a);
printf("aa->b=%d\n",aa->b);
printf("*********\n");
printf("bb->a=%d\n",bb->a);
printf("bb->b=%d\n",bb->b);
printf("bb->c=%d\n",bb->c);
printf("bb->d=%d\n",bb->d);
printf("*********\n");
printf("cc->a=%d\n",cc->a);
printf("cc->b=%d\n",cc->b);
printf("cc->c=%d\n",cc->c);
printf("cc->d=%d\n",cc->d);
return 0;
}
int main()
{
mytest(1,2);
return 0;
}
2. 运行结果
# ./qzzh
aa->a=0
aa->b=0
*********
bb->a=0
bb->b=0
bb->c=3
bb->d=4
*********
cc->a=0
cc->b=0
cc->c=3
cc->d=4
3.解释
struct A中的data[0]代表A可变长度,因此malloc时要把这长度一起malloc出来,这样就可以用了。
阅读(651) | 评论(0) | 转发(0) |