为多维数组分配内存
allocate memory for multidimensional array
我想将数组 A,B 相乘。这些数组的大小是固定的。我用模板推断它们的大小。现在我想为 C 分配一些等于 A*B 的内存。我的问题是当我这样做时(N = 3,L = 5(
int (*C)[N][L] = new int[N][L]
我得到
error: cannot convert ‘int (*)[5]’ to ‘int (*)[3][5]’ in initialization
.
我做了一个解决方法,但仍然想知道没有解决方法如何做到这一点。
template<int N, int K>
struct matrix {
int array[N][K];
};
template<int N, int K, int L>
int (&multiply(int (&A)[N][K], int (&B)[K][L]))[N][L] {
matrix<N,L> *mat = new matrix<N,L>();
int (&C)[N][L] = mat->array;
return C;
}
int main() {
int A[3][4];
int B[4][5];
int (&C)[3][5] = multiply(A, B);
}
您可以使用typedef
或reinterpreted_cast
制作其他解决方案,但为什么需要它们?这就像 c++ 本身的失败,语言未能兑现承诺。它类似于Java中的泛型。您认为像List<T>
这样的容器会知道得更好,但它们在铸造和@SuppressWarnings
方面遵循相同的错误方式。
int (*C)[N][L] = new int[N][L];
是new T[n]
返回指向T
的指针。已分配数组的事实在返回类型中不可见。因此,表达式 new int[N][L]
返回一个指向 size- L
int
数组的指针。这就是您在 LHS 上需要的类型:
int (*C)[L] = new int[N][L];
相关文章:
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 如果 const 不分配内存,为什么我可以获取 const 的地址?
- 在函数中分配内存时出现问题
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- constexpr new 如何分配内存?
- 在构造函数中分配内存失败是如何冒泡的
- LLVM 传递以在特定地址分配内存
- CudaMalloc 在分配内存时失败
- 为什么它在不分配内存的情况下工作正常
- 为什么在正确解除分配内存时出现内存泄漏?
- 如何通过 malloc 为队列数组分配内存?
- vector是否为std::移动的对象连续分配内存
- 删除类成员的动态分配内存的最佳方法是什么
- 唯一指针是否在堆或堆栈上分配内存?
- 如果不分配内存,我如何能够为变量创建和分配值?
- std::initializer_list 堆是否分配内存?
- 如何按顺序或在指定的地址分配内存?
- 是否可以使用 malloc 为类对象分配内存?
- 迭代器是否分配内存(如指针)?