如何在C中分配内存中存储不同类型?
我的问题是如何将不同类型存储到该内存中并打印它。具体来说,我需要 3x char、1x float 和 1x int。
My question is how to store different types to that memory and print it. specifically I need 3x char, 1x float, and 1x int.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果没有关于作业的更广泛的上下文,就不可能确定您的导师正在寻找的解决方案,但需要明确的是
malloc()
返回一个指向内存的空指针,保证以某种方式对齐解释为任何基本类型。这里使用 uint16_t 看起来相当随意,可能是为了测试您对指针概念和类型转换的了解。 5 字节长度的奇怪选择也可能是为了强调这样一个事实:空间只需要足够大来容纳要存储的最大对象。
这似乎是学校作业中喜爱的任务之一,但不一定鼓励良好的编码实践。也就是说,可能需要以下“肮脏”解决方案:
一个更复杂的解决方案,可能会超越您的课程材料,那就是使用联合:
如果特定分配行是“必需的”,那么您可以使用命名联合并投射
内存
:Without wider context about the assignment it is not possible to determine the solution your tutor is looking for, but to be clear
malloc()
returns a void pointer to memory guaranteed to be aligned in a manner that can be interpreted as any fundamental type.The use of
uint16_t
here seems rather arbitrary, and is presumably chosen to test you knowledge of pointer concepts and type casts. The strange choice of 5 byte length may also be contrived to highlight the fact that the space need only be large enough to hold the largest object to be stored.This appears to be one of those tasks beloved of school assignments that do not necessarily encourage good coding practice. That said, the following 'dirty' solution may be what is sought:
A more sophisticated solution, that may be stepping beyond your course material is to use a union:
If the specific allocation line is "required" then you can use a named union and cast
memory
: