为多维数组分配内存

allocate memory for multidimensional array

本文关键字:分配 内存 数组      更新时间:2023-10-16

我想将数组 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);
}

您可以使用typedefreinterpreted_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];