指针相关

#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函数地址。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值