【发布时间】:2017-11-12 13:11:28
【问题描述】:
我在做一个 ctf 问题,有一行我看不懂。
int (*fp)(char *)=(int(*)(char *))&puts, i;
谁能解释一下这是什么意思?
【问题讨论】:
我在做一个 ctf 问题,有一行我看不懂。
int (*fp)(char *)=(int(*)(char *))&puts, i;
谁能解释一下这是什么意思?
【问题讨论】:
fp 是一个指针
(*fp)
到函数
(*fp)(
接受 1 个 char 类型的参数
(*fp)(char)
并返回int类型的值
int (*fp)(char)
经过大部分冗余转换后,指针被初始化为puts的地址。
int (*fp)(char *)=(int(*)(char *))&puts
int (*fp)(char *)=(int(*)(char *))puts // & redundant
int (*fp)(const char *)=puts
对象i 未初始化。它的类型为int
int (*fp)(char *)=(int(*)(char *))&puts, i;
【讨论】:
首先有一个变量声明:
int (*fp)(char *)
fp 是一个指向函数的指针,它接受一个char * 参数并返回int。
然后fp被初始化为一个值:
(int(*)(char *))&puts
该值为puts函数的地址,转换为与fp相同的类型。
最后,还有一个变量声明:
int /* ... */, i;
【讨论】:
这个声明有两个部分:
int (*fp)(char *)=(int(*)(char *))&puts, i;
第一个是:int (*fp)(char *)=(int(*)(char *))&puts;
解释:这是在单个语句中的函数指针声明和初始化。其中fp 是指向函数puts 的指针。如果您打印fp 和puts 的值,它们将具有相同的值,即puts 的地址。
#include<stdio.h>
int main()
{
int (*fp)(char *)=(int(*)(char *))&puts, i;
printf("puts %p\n",puts);
printf("fp %p\n",fp);
}
而秒是:int i;
【讨论】: