将内存分配返回值强制转换为 TYPE 数组



试图在VisualStudio中执行以下操作,但没有成功。 基本上我得到了类型TypeA我想创建一个TypeA数组,比方说TypeA array[10];

但是我希望数组在堆上而不是在堆栈上,因为它会很大(比如0x200000(或其他东西。

因此,我尝试在代码方面做的是如下所示:

struct TypeA {
UINT64 a;
UINT64 b;
UINT64 c;
UINT64 d;
};
TypeA array[0x10000] = (TypeA[0x10000])malloc(sizeof(TypeA)*0x10000);

根据您的评论,在我看来,您想要类似的东西

template<typename T, std::size_t N>
struct array_wrapper {
T array[N];
// might extend with the remaining `std::array` interface
};
//...
auto array = std::make_unique<array_wrapper<TypeA, 0x10000>>();
some_library_function(array->array);

这样some_library_function将看到一个内置数组TypeA和长度0x10000,但具有动态存储持续时间。


请注意,我没有使用std::array,因为我不确定是否有一种有保证的合法方式可以从中获取对底层数组(而不是其第一个元素(的引用,即使使用reinterpret_cast也是如此。至少可以肯定的是,如果TypeA不是标准布局类型,就不会有。


另请注意,std::make_unique将对数组进行值初始化,这意味着它将对所有元素进行清零。如果您有一些特定的性能原因来避免这种情况,您可以在 C++20 中改用std::make_unique_default_init或在此之前(不太理想(:

using array_type = array_wrapper<TypeA, 0x10000>;
auto array = std::unique_ptr<array_type>(new array_type);

与所有动态数组一样,请使用std::vector.

std::vector<TypeA> array(0x10000);

尝试

struct TypeA* array = malloc(0x10000 * sizeof(struct TypeA));

编辑:对不起,这是C

你不能有数组。TypeA array[0x10000]在堆栈上声明一个0x10000元素数组。结束。句点。

但是,您可以有一个指向堆栈上数组开头的指针。这是通常的做法:

TypeA *array = (TypeA*)malloc(sizeof(TypeA)*0x10000);

由于这是C++而不是 C,因此您应该为此目的使用new。请注意,如果TypeA有一个构造函数,malloc不会调用它,但new会调用它。

TypeA *array = new TypeA[0x10000];

不要忘记使用free(对于malloc( 或delete [](对于new []( 来释放数组

你也可以分配一个std::array:(这算作一个对象,所以用delete而不是delete[]删除它(

std::array<TypeA, 0x10000> *array = new std::array<TypeA, 0x10000>;

最新更新