Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to allocate and deallocate 2D array dynamically in C++

1 Answer

0 votes
#include <iostream>

using std::cout;
using std::endl;

int **allocate2DArray(int row, int col)
{
	int **pp = new int*[row];

	for (int i = 0; i < row; i++)
		pp[i] = new int[col];
	
	return pp;
}

void delete2DArray(int **pp, int row)
{
	for (int i = 0; i < row; i++)
		delete[] pp[i];
	
	delete[] pp;
}

void init(int **pp, int row, int col)
{
	for (int i = 0; i < row; i++)
		for (int j = 0; j < col; j++)
			pp[i][j] = i * j + 1;
}

void print(int **pp, int row, int col)
{
	for (int i = 0; i < row; i++)
	{
		for (int j = 0; j < col; j++)
			cout << pp[i][j] << " ";

		cout << endl;
	}
}


int main()
{
	int row = 3, col = 4;
	int **arr2d = allocate2DArray(row, col);

	init(arr2d, row, col);

	print(arr2d, row, col);

	delete2DArray(arr2d, row);

	return 0;
}


/*
run:

1 1 1 1
1 2 3 4
1 3 5 7

*/

 



answered Feb 18, 2018 by avibootz
edited Feb 18, 2018 by avibootz

Related questions

...