问题
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