函数指针的大小有什么保证? [英] What is guaranteed about the size of a function pointer?

查看:25
本文介绍了函数指针的大小有什么保证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C 中,我需要知道结构体的大小,其中包含函数指针.我可以保证在所有平台和架构上都可以:

In C, I need to know the size of a struct, which has function pointers in it. Can I be guaranteed that on all platforms and architectures:

  • void* 的大小与函数指针的大小相同吗?
  • 函数指针的大小不会因其返回类型而不同吗?
  • 函数指针的大小不会因参数类型的不同而不同吗?

我认为所有这些答案都是肯定的,但我想确定一下.对于上下文,我正在调用 sizeof(struct mystruct),仅此而已.

I assume the answer is yes to all of these, but I want to be sure. For context, I'm calling sizeof(struct mystruct) and nothing more.

推荐答案

来自 C99 规范,第 6.2.5 节,第 27 段:

From C99 spec, section 6.2.5, paragraph 27:

指向 void 的指针应具有相同的表示和对齐要求作为指向 a 的指针字符类型.同样,指针到合格或不合格的版本兼容类型应具有相同的表示和对齐要求.所有指向结构类型应具有相同的表示和对齐相互要求.全部指向联合类型的指针应具有相同的表示和对齐相互要求.指针其他类型不需要有相同的代表或对齐要求.

A pointer to void shall have the same representation and alignment requirements as a pointer to a character type. Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.

所以不;不保证 void * 可以保存函数指针.

So no; no guarantee that a void * can hold a function pointer.

以及第 6.3.2.3 节第 8 段:

And section 6.3.2.3, paragraph 8:

指向一种类型的函数的指针可以转换为指向 a 的指针另一种类型和返回的功能再次;结果比较相等到原始指针.

A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer.

暗示一种函数指针类型可以保存任何其他函数指针值.从技术上讲,这与保证函数指针类型的大小不能变化不同,仅仅保证它们的值占据相同的范围.

implying that one function pointer type can hold any other function pointer value. Technically, that's not the same as guaranteeing that function-pointer types can't vary in size, merely that their values occupy the same range as each other.

这篇关于函数指针的大小有什么保证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆