在 C 中将 double 转换为 void* [英] Converting double to void* in C

查看:98
本文介绍了在 C 中将 double 转换为 void*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个解释器,我希望能够将函数返回的任何值存储到空指针中.我将整数和各种指针存储为空指针没有问题,但是在尝试将双精度转换为空指针时出现错误.我知道双精度数的存储方式与位级别的整数和指针不同,但我不明白为什么我不能将我想要的任何位放入指针中(假设它分配了足够的内存),然后再将它们取出,将它们转换为双重身份.

I'm writing an interpreter and I'd like to be able to store whatever value a function returns into a void pointer. I've had no problem storing ints and various pointers as void pointers but I get an error when trying to cast a double as a void pointer. I understand that doubles are stored differently than integers and pointers at the bit level, but I don't understand why I can't place whatever bits I want into the pointer (assuming it has enough memory allocated) and then take them out later, casting them as a double.

是否可以使用我不知道的语法将 double 转换为 void 指针,或者我是否误解了 void 指针的工作原理?

Is it possible to cast a double to a void pointer using syntax I'm not aware of or am I misunderstanding how void pointers work?

推荐答案

在许多系统上,double 是 8 字节宽,指针是 4 字节宽.因此,前者不适合后者.

On many systems a double is 8 bytes wide and a pointer is 4 bytes wide. The former, therefore, would not fit into the latter.

您似乎在滥用 void*.您的解决方案将涉及分配至少与您需要以某种类似变体的结构存储的最大类型一样大的存储空间,例如联合.

You would appear to be abusing void*. Your solution is going to involve allocating storage space at least as big as the largest type you need to store in some variant-like structure, e.g. a union.

这篇关于在 C 中将 double 转换为 void*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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