您的位置:首页 > 其它

指针相关

2016-09-12 22:50 246 查看
#include<stdio.h>
#define _new(_struct, _init) (_init((_struct *)memset(malloc(sizeof(_struct)), 0, sizeof(_struct))))

void foo()
{
printf("fuck");
}

struct A
{
void (* fun)();
};

struct B
{
struct A parent;
};

struct B * b_init(struct B *_this)
{
_this->parent.fun = foo;
return _this;
}

void main()
{
struct A * s = (struct A *)_new(struct B, b_init);
s->fun();
getchar();
}


首先定义了 A 结构体

在 A 结构体里面只有一个 返回为void 类型的函数,其中 fun指向真正的函数地址。

然后定义了 B 结构体

在 B 结构体里面 定义了一个 A 结构体类型的变量 parent 。

define了一个宏 _new 。

void *malloc(size_t size);

向系统申请分配指定size个字节的内存空间。

void *memset(void *s, int ch, size_t n);

将s中当前位置后面的n个字节 (typedef unsigned int size_t )用 ch 替换并返回 s 。

实际上 struct A * s = (struct A *)_new(struct B, b_init);这句语句 中的(struct A *)并没有什么用,因为b_init函数返回的是地址,而s指针也是地址。
struct A * s = _new(struct B, b_init);该语句就是将一个指向struct A 类型的地址的指针 s 指向 struct B 的首地址 。
因为 B 中只有一个 A类型的变量 parent 。所以 B 的首地址,就是parent的首地址。

既然 s 指向的是parent的地址,那么s->fun() 函数地址当然就是 b_init 中设置过的foo函数地址。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: