一段奇妙的C语言代码的实现

本文通过一个具体的C语言示例介绍了如何使用结构体指针来操作成员变量,并展示了如何将当前结构体实例设置为全局变量进行访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看gdb源码的时候无意发现一个奇怪的写法, 仔细查看了之后明白了其中的秘密

fun()->mem1 = xx;
fun()->mem2(4);

 这是我实现的一个代码:

#include <stdio.h>
#include <stdlib.h>

typedef int (*print_fun_t)(const char *, ...);

struct inferior
{
    int attach_flag;
    print_fun_t print;
};

/* The Current Inferior.  */
static struct inferior *current_inferior_ = NULL;

struct inferior*
current_inferior (void)
{
    return current_inferior_;
}

void
set_current_inferior (struct inferior *inf)
{
    current_inferior_ = inf;
}

int main()
{
    struct inferior *inf;
    inf = (struct inferior *)malloc(sizeof(struct inferior));
    inf->print = printf;

    set_current_inferior(inf);

    current_inferior()->attach_flag = 10;

    current_inferior()->print("my attach_flag: %d\n", current_inferior()->attach_flag);

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值