指针的大小可以在数据指针和函数指针之间变化吗? [英] Can the size of pointers vary between data and function pointers?

查看:28
本文介绍了指针的大小可以在数据指针和函数指针之间变化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚阅读了关于指针的 C 常见问题解答的部分.

I was just reading the section of the C FAQ on pointers.

它讨论了不能使用 void * 指针来保存函数指针,因为数据指针和函数指针在某些平台上可能具有不同的大小,而 void * 是只保证足够大以保存指向数据的指针.

It discusses not being able to use void * pointers to hold function pointers because pointers to data and pointers to functions may have differing sizes on some platforms and void * is only guaranteed be large enough to hold pointers to data.

谁能举一个平台的例子,其中指向数据的指针和指向函数的指针实际上具有不同的大小?

Can anyone give an example of a platform where pointers to data and pointers to functions actually have differing sizes?

推荐答案

> type ppp.c
#include <stdio.h>
#include <stdlib.h>

int global = 0;

int main(void) {
    int local = 0;
    static int staticint = 0;
    int *mall;
    int (*fx)(void);

    fx = main;
    mall = malloc(42); /* assume it worked */
    printf("#sizeof pointer to local: %d
", (int)sizeof &local);
    printf("#sizeof pointer to static: %d
", (int)sizeof &staticint);
    printf("#sizeof pointer to malloc'd: %d
", (int)sizeof mall);
    printf("#sizeof pointer to global: %d
", (int)sizeof &global);
    printf("#sizeof pointer to main(): %d
", (int)sizeof fx);
    free(mall);
    return 0;
}
> tcc -mc ppp.c
Turbo C  Version 2.01 ...
warnings about unused variables elided ...
Turbo Link  Version 2.0 ...
> ppp
#sizeof pointer to local: 4
#sizeof pointer to static: 4
#sizeof pointer to malloc'd: 4
#sizeof pointer to global: 4
#sizeof pointer to main(): 2
> tcc -mm ppp.c
> ppp
#sizeof pointer to local: 2
#sizeof pointer to static: 2
#sizeof pointer to malloc'd: 2
#sizeof pointer to global: 2
#sizeof pointer to main(): 4

tcc -mc 在紧凑"模型中生成代码;tcc -mm 在中等"模型中生成代码

tcc -mc generates code in the "compact" model; tcc -mm generates code in the "medium" model

这篇关于指针的大小可以在数据指针和函数指针之间变化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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