如何存储在内存中的对象的数组? [英] How is an array of objects stored in memory?

查看:131
本文介绍了如何存储在内存中的对象的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道一个连续的内存块被分配一个数组。

I know a contiguous block of memory is allocated for an array.

我的第一个问题是,当数组元素是一个对象,而不是一个内置式的,能存储在阵列保留的连续内存?指针为对象或对象的实际数据?我的猜测是指针数组中存储的和实际的对象是随机存储在堆中。我是不是正确的?

My first question is when the array element is an object rather than a built-in type, what gets stored in the contiguous memory reserved for the array? Pointer for the object or the actual data for the object? My guess is pointers are stored in the array and the actual objects are stored randomly in the heap. Am I correct?

我的第二个问题是现在我们要保留一个指定的内存(例如,共享内存)为对象的数组。什么是实现这一目标的最佳途径?我应当由一个连载指定内存中的一个实际的对象,并使用相对指针(例如,索引)来访问他们每个人的?

My second question is now we want to reserve a specified memory(e.g., shared memory) for an array of objects. What is the best way to achieve this? Should I serialise the actual objects in the specified memory one by one and use relative pointers(e.g., indices) to access each of them?

推荐答案

一点也不正确。数组 T [N] 包含类型的 N 元素 T ,直接存储在连续内存。该阵列占地 N * sizeof的(T)字节的内存。

Not at all correct. An array T[N] contains N elements of type T, directly stored in contiguous memory. The array occupies N * sizeof(T) bytes of memory.

相反,要回答你的第二个问题, N *的sizeof(T)任何运行字节的内存,可用于保存 N 类型的元素 T (如有可能还有一些对齐约束)。

Conversely, to answer your second question, any run of N * sizeof(T) bytes of memory can be used to hold N elements of type T (subject to some alignment constraints perhaps).

这篇关于如何存储在内存中的对象的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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