Allocate memory 2d array in function C++

六月ゝ 毕业季﹏ 提交于 2021-02-08 12:15:30

问题


I'm trying to dynamically allocate memory for a 2D array inside a function in C++. A question exactly like this has been asked except that it is written using malloc and dealloc, so I was wondering if you could help me convert it to use new and delete. Here is the other question:

Allocate memory 2d array in function C

I tried changing it to the following code, but I'm getting errors.

void assign_memory_for_board(int ROWS, int COLS, int *** board) {
   *board = new int**[ROWS];
   for (int i = 0; i < ROWS; i++) {
       (*board)[i] = new int*[COLS];
   }
}

Here is the answer that worked using malloc and dealloc:

void allocate_mem(int*** arr, int n, int m)
{
   *arr = (int**)malloc(n*sizeof(int*));
   for(int i=0; i<n; i++)
      (*arr)[i] = (int*)malloc(m*sizeof(int));
} 

Thank you!


回答1:


You have extra stars. The function should be

void assign_memory_for_board(int ROWS, int COLS, int *** board) {
   *board = new int*[ROWS];
   for (int i = 0; i < ROWS; i++) {
       (*board)[i] = new int[COLS];
   }
}



回答2:


try it

int AllocMatrix(int ***K, int h, int c){
    *K = new int *[h];
    for(int i=0; i < h; i++){
        *K[i] = new int[c];
    }
    if(K == NULL){
        return 0;
    }
    cout<<"Avaiable!"<<endl;
    return 1;
}


来源:https://stackoverflow.com/questions/35857640/allocate-memory-2d-array-in-function-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!