如何将动态内存分配给int [4] [3]数组

时间:2013-10-17 08:12:34

标签: c++ c

如何将运行时内存分配给size[4][3]数组?

int a[4][3]

如果需要在运行时为数组分配内存,而不是如何将内存分配给2D数组或3D数组。

8 个答案:

答案 0 :(得分:2)

根据评论编辑答案。为每个维度单独分配。对于2D阵列,需要2级分配。

*a = (int**)malloc(numberOfRows*sizeof(int*));
for(int i=0; i<numberOfRows; i++)
    {
    (*arr)[i] = (int*)malloc(numberOfColumns*sizeof(int));
    }

答案 1 :(得分:1)

动态分配int [4] [3]类型数组的最简单方法是以下

int(* a)[3] = new int [4] [3];

//使用数组的一些东西

删除[] a;

另一种方法是分配几个数组。例如

int ** a = new int * [4];

for(size_t i = 0; i&lt; 4; i ++)a [i] = new int [3];

//使用数组的一些东西

for(size_t i = 0; i&lt; 4; i ++)delete [] a [i];

删除[] a;

答案 2 :(得分:1)

你有什么尝试。 new int[4][3]是完全有效的 表达式,结果可以用。赋值给变量 适当的类型:

int (*array2D)[3] = new int[4][3];

话虽如此:我真的不能想到这样的情况 是合适的。实际上,随时都可以 一个二维数组,你应该定义一个类 实现它(使用std::vector<int>作为实际内存)。

答案 3 :(得分:0)

使用calloc,我想这样做。

int **p;
p=(int**)calloc(4,sizeof(int));

答案 4 :(得分:0)

在C中你可以使用指向指针的指针

<@> AS @Lundin提到这不是2D阵列。它是一个查找表,使用指向遍布堆的分段内存区域的指针。

您需要分配所需的指针数,然后分配每个指针。您可以根据需要分配固定大小或可变大小

  //step-1: pointer to row
  int **a = malloc(sizeof(int *) * MAX_NUMBER_OF_POINTERS);
  //step-2: for each rows
  for(i = 0; i < MAX_NUMBER_OF_POINTERS; i++){
    //if you want to allocate variable sizes read them here
    a[i] = malloc(sizeof(int) * MAX_SIZE_FOR_EACH_POINTER);  // where as if you use character pointer always allocate one byte extra for null character
  } 

如果您想要分配char指针,请避免在for循环中使用sizeof(char)。因为sizeof(char) == 1do not cast malloc result

请参阅How to declare a 2d array in C++ using new

答案 5 :(得分:0)

纯C方法如下:

int (*size)[4][3];

size = malloc(sizeof *size);

/* Verify size is not NULL */

/* Example of access */
(*size)[1][2] = 89;

/* Do something useful */

/* Deallocate */
free(size);

好处是通过不分配中间指针消耗更少的内存,处理单个内​​存块并且释放更简单。如果您开始拥有超过2个维度,这一点尤其重要。

缺点是访问语法更复杂,因为您需要在能够索引之前取消引用指针。

答案 6 :(得分:0)

您可以使用std::vector<>,因为它是模板化容器(意味着数组元素可以是您需要的任何类型)。 std::vector<>允许动态内存使用(您可以随时更改向量的大小&lt;&gt; ...内存已自动分配和释放。)

例如:

#include <iostream>
#include <vector>

using namespace std; // saves you from having to write std:: in front of everthing

int main()
{
    vector<int> vA;
    vA.resize(4*3); // allocate memory for 12 elements

    // Or, if you prefer working with arrays of arrays (vectors of vectors)
    vector<vector<int> > vB;
    vB.resize(4);
    for (int i = 0; i < vB.size(); ++i)
        vB[i].resize(3);

    // Now you can access the elements the same as you would for an array
    cout << "The last element is " << vB[3][2] << endl;
}

答案 7 :(得分:-2)

您可以在c ++中使用malloc()或在c ++中使用new来进行动态内存分配。