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!
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];
}
}
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;
}
Related
I'm working with c++ arrays and I found a problem. I can easily do the exercise using cin and filling array with for loop. But when I try to do it as filled array I got the error with too many initializer values. How to solve it?
#include <iostream>
using namespace std;
void func(int **arr, int row, int col)
{
for (int i=0; i<row; i++)
{
for(int j=0 ; j<col; j++)
{
cout<<arr[i][j]<<" ";
}
printf("\n");
}
}
int main()
{
int row = 2;
int colum = 2;
int** arr = new int*[row];
for(int i=0; i<row; i++)
{
arr[i] = new int[colum];
}
arr = {
{1,2},
{3,4}};
func(arr, row, colum);
return 0;
}
arr is a pointer
int** arr = new int*[row];
So it may be initialized with a braced list containing only one (assignment) expression.
For the allocated array of two elements you could write for example
int** arr = new int*[row];
for(int i=0; i<row; i++)
{
if ( i == 0 ) arr[i] = new int[colum] { 1, 2 };
else arr[i] = new int[colum] { 3, 4 };
}
or
int** arr = new int*[row];
for(int i=0, value = 1; i<row; i++)
{
arr[i] = new int[colum] { value++, value++ };
}
Pay attention to that you will need to free the dynamically allocated memory for the arrays.
Otherwise use the standard container std::vector<std::vector<int>> instead of the allocated dynamically arrays.
I am trying to define a 2D array, but I want to do it in a function,
here is my code:
int** createArray( int columns, int rows)
{
int** array[rows];
for(int i = 0; i < rows; i++)
{
array[i] = new int*[columns];
}
for(int i = 0; i <columns; i++)
{
for(int j = 0; j < rows; j++)
{
array[i][j] = 0;
std::cout <<array[i][j];
}
std::cout<<"\n";
}
return *array;
}
int main()
{
int **myArray = createArray(3,5);
for(int k =0; k < 5; k++)
{
if( (myArray[0][k] == 0) && (&myArray[1][k] == 0)) //segmentation fault
{
myArray[2][k] = 10; //segmentation fault
}
delete[] myArray;
}
But it causes errors which can be seen as comments in lines. I am new to C++ and I do not know how to fix this.
Thank you very much
Prefer std::vector over manual memory management:
std::vector<std::vector<int>> createArray(int columns, int rows)
{
return std::vector<std::vector<int>(rows, std::vector<int>(columns));
}
int main()
{
int COLUMNS = 5;
int ROWS = 3;
auto myArray= createArray(COLUMNS, ROWS);
/*
Do stuff
*/
//std::vector handles delete on it's own, no need to clean up
}
If you cannot use std::vector for some reason, this is the a way to initialize 2D array on the heap:
int** createArray(int columns, int rows)
{
int** arr = new int*[rows];
for(int i = 0; i < rows; ++i)
{
arr[i] = new int[columns];
}
return arr;
}
int main()
{
int COLUMNS = 5;
int ROWS = 3;
int** myArray= createArray(COLUMNS, ROWS);
/*
Do stuff
*/
//you need to a delete for every new and delete[] for every new[]
for(int i = 0; i < rows; ++i)
{
delete[] myArray[i];
}
delete[] myArray;
}
I have a question as follows:
I declared two pointer-to-pointer double-type variables **matrix1 and **matrix2 and allocate them by new operator to become 2D arrays.
First I used for loop to make matrix1 point to double-type data called element, then I copy matrix1 to matrix2, which means matrix2 points to element too. Then problem comes: I used delete operator to terminate matrix1 after copying, but then the values matrix2 point to became extremely strange. I think that was because after deleting matrix1, element terminates, so I think one of a solution is let matrix2 point to other address with the values same with element. But I don't know how to do this(copy element to new dynamic memories and won't disappear after deleting matrix1) in an efficient way, can somebody help me? thank you.
void MatCpy(double **InMat, double **OutMat, int NumOfRow, int NumOfCol)
{
for (int j = 0; j < NumOfRow; j++)
{
for (int i = 0; i < NumOfCol; i++)
{
OutMat[j][i] = InMat[j][i];
}
}
}
double **Malloc2D_Dbl(int row, int col)
{
double **data = new double*[row];
for (int i = 0; i < row; i++)
data[i] = new double[col];
return data;
}
void load(char *load_path, double **data, int height, int width) // function for loading
{
int i = 0, j = 0;
char buffer[30];
file_handle = fopen (load_path, "r");
for (int k = 0; k < width*height; k++)
{
fscanf (file_handle, "%s", &buffer);
j = k / width;
i = k % width;
data[j][i] = atof(buffer);
}
fclose (file_handle);
}
Sorry I am a noob....
More efficient than copying the individual elements is to use memcpy like this:
void MatCpy(double **InMat, double **OutMat, int NumOfRow, int NumOfCol) {
for(int j=0; j<NumOfRow; j++) {
memcpy(OutMat[j], InMat[j], NumOfCol*sizeof(double));
}
}
It's been a while since I last visited arrays (I've been working with vectors recently) and I need to convert an 2D vector back into a 2D array because of a library I am using accepts the paramaters of type double array where the accessors of this array is foo[i][j] for example.
Here is my code:
double** setupHMM(vector<vector<double> > &vals, int N, int M)
{
double** temp;
temp = new double[N][M];
for(unsigned i=0; (i < N); i++)
{
for(unsigned j=0; (j < M); j++)
{
temp[i][j] = vals[i][j];
}
}
}
And with this, I get error: ‘M’ cannot appear in a constant-expression
I have also tried the following:
double** setupHMM(vector<vector<double> > &vals, int N, int M)
{
double** temp;
for(unsigned i=0; (i < N); i++)
{
temp[i] = new double[N];
for(unsigned j=0; (j < M); j++)
{
temp[j] = new double[M];
temp[i][j] = vals[i][j];
}
}
}
However, this produces a segmentation fault 11.
Could anyone suggest any advice, or, a better way to convert a vector to a 2D array..
Thanks
You were close. It should be:
double** setupHMM(vector<vector<double> > &vals, int N, int M)
{
double** temp;
temp = new double*[N];
for(unsigned i=0; (i < N); i++)
{
temp[i] = new double[M];
for(unsigned j=0; (j < M); j++)
{
temp[i][j] = vals[i][j];
}
}
}
A double pointer (double**) is not convertible to a 2D array.
double** temp;
temp = new double[N][M]; //invalid
double** temp;
temp = new double(*)[M];
It's a common misunderstanding to think that because an 1D array decays to a pointer that therefore a 2D array will decay to a double pointer. This is not true. The decay only happens with a single pointer.
replace
temp[i] = new double[N];
with
temp = new double*[N];
in the second code, and move it outside the loop
I have this 2d dynamic array and I want to pass it to a function, How would I go about doing that
int ** board;
board = new int*[boardsize];
//creates a multi dimensional dynamic array
for(int i = 0; i < boardsize; i++)
{
board[i] = new int[boardsize];
}
int **board;
board = new int*[boardsize];
for (int i = 0; i < boardsize; i++)
board[i] = new int[size];
You need to allocate the second depth of array.
To pass this 2D array to a function implement it like:
fun1(int **);
Check the 2D array implementation on below link:
http://www.codeproject.com/Articles/21909/Introduction-to-dynamic-two-dimensional-arrays-in
You should define a function to take this kind of argument
void func(int **board) {
for (int i=0; i<boardsize; ++i) {
board[i] = new int [size];
}
}
func(board);
If boardsize or size are not globlal, you can pass it through parameters.
void func(int **board, int boardsize, int size) {
for (int i=0; i<boardsize; ++i) {
board[i] = new int [size];
}
}
func(board, boardsize, size);
You can pass a pointer to an pointer:
void someFunction(int** board)
{
}
Small code for creation and passing a dynamic double dimensional array to any function.
`
void DDArray(int **a,int x,int y)
{
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<5;j++)
{
cout<<a[i][j]<<" ";
}
cout<<"\n";
}
}
int main()
{
int r=3,c=5,i,j;
int** arr=new int*[r];
for( i=0;i<r;i++)
{
arr[i]=new int[c];
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
cout<<"Enter element at position"<<i+1<<j+1;
cin>>arr[i][j];
}
}
DDArray(arr,r,c);
}
`