将内存分配返回值强制转换为 TYPE 数组
Casting memory allocation return value to array of 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>;
- 将内存分配返回值强制转换为 TYPE 数组
- C++ 嵌套类模板 错误 C2440 '=':无法从'type'转换为'same type'
- 为什么指针没有隐式转换为 <type> const*const
- 从整数到枚举的首选转换样式 QEvent::Type
- c++ C2440 错误无法从"const BWAPI::UpgradeType"转换为"const BWAPI::Type *"
- C++ 错误 C2662 无法将"this"指针从"const Type"转换为"Type &"
- 错误 C2440: 'type cast':无法从 'bool' 转换为 'CString'
- 无法将参数 1 从"cli::interior_ptr<Type>"转换为"CvCapture **"
- 将 MSVS 2010 项目转换为 MSVS 2012 RC,但出现错误"The C++ standard doesn't provide a hash for this type"
- 专用转换函数导致"ambiguous default type conversion"错误 (c++)
- vector::p ush_back 从 const Type* 转换为 type*
- 可以安全地使用静态强制转换,为每个实例使用唯一的虚拟 int type() 来提高性能
- 无法将参数 1 从"cli::array<Type> ^"转换为"无符号短整型"
- 无法从 Type* 转换为 Type&&
- 没有匹配的操作数[template]/无法从Type const*转换为Type
- C++ std::映射分配错误:无法在赋值中将' type **'转换为'type *'
- 错误 C2440 '=' : 无法从 'cli::array ^'<Type> 转换为 'wchar_t'
- ' auto x = type{…} '初始化语法和'显式'转换操作符- clang vs gcc
- 将Type**转换为void*,然后再返回到Type*
- 简单的模板化函数,用于转换 std::vectors - "illegal use of this type as an expression"