1

我正在使用以下代码创建动态二维数组。

uint32_t** arrays = new uint32_t*[1000]; 
uint32_t number = take input from console ;
arrays[0] = new uint32_t[number];
number = take input from console ;
arrays[1] = new uint32_t[number];
delete arrays[0] ;
number = take input from console ;
arrays[0] = new uint32_t[number] ;

我正在使用 64 位 Unix 机器来执行上述代码。

在上面的代码中,机器使用 64 位指针指向二维数组,这就是代码占用更多空间的原因。

谁能帮助我,如何转换代码,因此它需要 32 位指针?或者另一种解决空间复杂性的方法?我不想使用向量的向量,因为我的教授没有要求这样做。

4

4 回答 4

2

Actually, your code is already pretty much memory optimized as it is.

You allocate a 1000 64-bit pointers in your first line. That's unavoidable since that is what your machine uses. However, that only takes 8000 bytes, hardly worth the effort optimizing these days.

In the next lines, you dynamically allocate space for int32_t arrays, which only take 4 bytes per entry. So if you allocate 30 million entries, it will take 120.000.000 bytes. I think you are mistaken in thinking that this secondary array will take 30 million * 8 bytes = 240.000.000 bytes, which it doesn't. Only the pointer is 64 bit, the data itself will take up as much or as little space as it needs.

Addendum: I want to add that allocating a two dimensional array, as some have suggested, will actually waste more memory, since your clearly don't know how long each secondary entry will be. Your solution allocates only as much space as needed.

于 2012-12-31T14:49:56.000 回答
1

您无法控制系统上的指针大小。

选择不关心,或者更好的是,使用实际的二维数组而不是指针数组。

于 2012-12-31T13:55:09.460 回答
1

这可能是一个疯狂的想法,但同样,您的问题也不是最标准的。

为什么不只使用堆基地址的偏移量?您将被限制为 32 位堆地址空间(4GB 堆),但如果您不想放弃 64 位指针所需的额外 4 个字节,那么您将很难克服这一限制。

这个想法是获取你的堆的基地址(可能,即使不是完全简单),它在一个全局变量中 - 让我们称之为 heap_base ......或类似的东西。

Now, when you create a pointer, don't store it's whole value in the first array, only store it's its offset (the difference) from heap_base.
When you want to access an element, restore the correct pointer value with addition.

This might not work - it depends on how the OS will allocate data on the heap - but I figured it might give you a nice idea for a solution.

于 2012-12-31T14:45:51.990 回答
0

另一种(更确切地说是 f*#@&d 向上的方式)查看它是使用 1 个 64 位指针来存储 2 个 32 位数字。所以有 64 位数字的数组,然后在每个元素中存储两个 32 位数字。

然后编写单独的方法,使用位操作和其他方式将这些访问为 32 位值,例如您的 get 看起来像这样。


uint32_t get (int i, int j)
{
   if (j % 2 == 0) 
    {
      return array[i][j/2] % (2^32)
    }
    else
    {
      return array[i][j/2] / (2^32)
    }
};

于 2012-12-31T14:10:28.950 回答