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);
}
`
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'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;
}
I 'm still newbie in C++, so don't be mean to me. I would like to know how to initialize 2 dimentional array in the void function.
This is my example code but it gives me exceptions about access violation locations instead:
#include "stdafx.h"
void matrixInit(char***);
void matrixDel(char**);
void main(void){
char** game=0;
matrixInit(&game);
matrixDel(game);
return;
}
void matrixInit(char*** matrix) {
matrix = new char**[3];
for (int i(0); i < 3; i++) {
matrix[i] = new char*[3];
for (int j(0); j < 3; j++)
*matrix[i][j] = '0';
}
return;
}
void matrixDel(char** matrix) {
for (int i(0); i < 3; i++)
delete[] matrix[i];
delete[] *matrix;
return;
}
Props to #fireant for the help with allocating the array. After some research and debugger plays, I figure all it out. I hope this solution will help someone in the future!
#include "stdafx.h"
using namespace std;
int** matrixInit(int, int);
void matrixInit(int***, int, int);
void matrixDel(int**, int);
void matrixFill(int**, int, int);
void matrixPrint(int**, int, int);
void main(void) {
const int rows = 3, cols = 3;
int** game;
matrixInit(&game, rows, cols); //Void allocation
//game = matrixInit(rows, cols); //Alternative allocation
matrixFill(game, rows, cols);
matrixPrint(game, rows, cols);
matrixDel(game, rows);
cout << endl << "Passed!"; //<iostream> lib required
_getch(); //<conio.h> lib required
return;
}
//Dynamical array allocation void function
void matrixInit(int*** matrix, int nRow, int nColumn) {
(*matrix) = new int*[nRow];
for (int i(0); i < nRow; i++)
(*matrix)[i] = new int[nColumn];
}
//Dynamical array allocation pointer return function
int** matrixInit(int nRow, int nColumn) {
int** matrix = new int*[nRow];
for (int i(0); i < nRow; i++)
matrix[i] = new int[nColumn];
return matrix;
}
//Dynamical array deallocation void function
void matrixDel(int** matrix, int nRow) {
for (int i(0); i < nRow; i++)
delete[] matrix[i];
delete[] matrix;
}
//Fill array void function
void matrixFill(int** matrix, int nRow, int nColumn) {
for (int i(0); i < nRow; i++)
for (int j(0); j < nColumn; j++)
matrix[i][j] = (j + 1) + (i * nRow);
}
//Print array void function
void matrixPrint(int** matrix, int nRow, int nColumn) {
for (int i(0); i < nRow; i++)
for (int j(0); j < nColumn; j++)
cout << "[" << i << "][" << j << "] = " << matrix[i][j] << endl;
}
You're almost there,
void matrixInit(char*** matrix) {
(*matrix) = new char*[3];
for (int i(0); i < 3; i++) {
(*matrix)[i] = new char[3];
for (int j(0); j < 3; j++)
(*matrix)[i][j] = '0';
}
return;
}
You're passing the address matrixInit(&game), but matrix = new char**[3]; is overwriting the passed address. Thus, game in main is not pointing to the allocated memory. You could have written void matrixInit(char*** const matrix) to make sure you don't change the address accidentally inside the function. As a practice try to fix your delete function.
I'm new to C++ and currently I'm trying to implement 2D matrix from classes, this is my current code, right now I'm unable to create an instance of the matrix object, please leave me feedback what I need to fix.
*Updated: I have fixed some of the code, but the matrix doesn't print anything
#include <iostream>
#include <cstdlib>
using namespace std;
class Matrix
{
public:
Matrix(); //Default constructor
Matrix(int *row, int *col); //Main constructor
void setVal(int row, int col, int val); //Method to set the val of [i,j]th-entry
void printMatrix(); //Method to display the matrix
~Matrix(); //Destructor
private:
int row, col;
double **matrix;
//allocate the array
void allocArray()
{
matrix = new double *[*row];
for (int count = 0; count < *row; count++)
*(matrix + count) = new double[*col];
}
};
//Default constructor
Matrix::Matrix() : Matrix(0,0) {}
//Main construcor
Matrix::Matrix(int *row, int *col)
{
allocArray();
for (int i=0; i < *row; i++)
{
for (int j=0; j < *col; j++)
{
*(*(matrix + i) + j) = 0;
}
}
}
//destructor
Matrix::~Matrix()
{
for( int i = 0 ; i < row ; i++ )
delete [] *(matrix + i) ;
delete [] matrix;
}
//SetVal function
void Matrix::setVal(int row, int col, int val)
{
matrix[row][col] = val;
}
//printMatrix function
void Matrix::printMatrix()
{
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
cout << *(*(matrix + i) + j) << "\t";
cout << endl;
}
}
int main()
{
int d1 = 2;
int d2 = 2;
//create 4x3 dynamic 2d array
Matrix object(&d1,&d2);
object.printMatrix();
return 0;
}
Your line
Matrix object = new int **Matrix(d1,d2);
is wrong. Use simply
Matrix object(d1,d2);
no need for Java-like syntax which in fact in C++ means dynamic allocation: Matrix* object = new Matrix(d1,d2);
Instead of Matrix object = new int **Matrix(d1,d2); use Matrix* object = new Matrix(d1,d2);
Also, you will have to use object->printMatrix(); instead of object.printMatrix();