C ++数组分配 [英] C++ Array Allocation
问题描述
你好,
给出以下声明:
Hello,
Given the following declarations:
<br />
size_t const ARRAY_ROWS = 2000000000; // 2,000,000,000<br />
typedef double DoubleArray_T[ARRAY_ROWS];<br />
<br />
...<br />
<br />
int main(void)<br />
{<br />
DoubleArray_T * A1;<br />
}<br />
如何分配数组?
我尝试过:
How can I allocate the array?
I''ve tried:
<br />
A1 = new DoubleArray_T;<br />
会有人友好地让我偶尔通过即时消息问他们C ++问题吗?
如果可以的话,肯定会有所帮助...
Would anyone be kind enough to let me ask them C++ questions occasionally through Instant Messaging?
Sure would be helpful if I could...
推荐答案
如果您真的想分配2,000,000,000个双精度数组,为什么不直接这样做呢?
If you really want to allocate an array of 2,000,000,000 doubles why not just do it directly?
double *A1 = new double[ ARRAY_SIZE ];
如果要使用一个明确命名的大对象bin,请使用typedef并使用
If you want to have a distinctly named large object bin the typedef and use
struct DoubleArray_T
{
double data[ ARRAY_SIZE ];
};
DoubleArray_T *A1 = new DoubleArray_T;
反而.这使得数组的行为比typedef更像对象.请记住,typedef仅引入了另一种类型的别名,并且除非您知道自己在做什么,否则指向数组的指针(如DoubleArray_T *
在代码中一样)是真正的怪兽.在您的原始代码中,new DoubleArray_T
返回一个指向double的指针,而您试图将其分配给DoubleArray_T *
,这是不同的类型.
干杯,
灰
PS:经过编辑,使其看起来至少是英语
instead. This makes the array behave more like an object than the typedef does. Remember a typedef only introduces an alias for another type and that pointers to arrays (as DoubleArray_T *
was in your code) are really strange beasts unless you know what you''re doing. In your original code new DoubleArray_T
was returning a pointer to a double and you were trying to assign that to a DoubleArray_T *
, which are different types.
Cheers,
Ash
PS: Edited to make it at least look English
您真的要分配几乎16
GB 吗?
:)
Do you really want to allocate almost16
GB?
:)
我找到了一种方法.
这行得通,但我不喜欢它:
A1 = new DoubleArray_T[1];
还有别的办法吗?
绝对不建议使用硬编码的值.
一定有更好的方法...
I''ve found a way.
This works, but I don''t like it:
A1 = new DoubleArray_T[1];
Isn''t there another way?
Using hard-coded values is never recommended.
There must be a better way...
这篇关于C ++数组分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!