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

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,104 questions

40,777 answers

573 users

How to declare and use dynamic 2D array using new in C++

Learn & Practice SQL


71 views
asked Apr 29, 2017 by avibootz
edited Apr 12, 2018 by avibootz

1 Answer

0 votes
#include <iostream>

using namespace std;

int main()
{
	int rows = 3, cols = 4;

	
	// allocate array
	int **arr = new int*[rows];
	for (int i = 0; i < rows; i++)
		arr[i] = new int[cols];

	// set values
	for (int i = 0; i < rows; i++)
	{
		for (int j = 0; j < cols; j++)
			arr[i][j] = i + j;
	}

	// print values
	for (int i = 0; i < rows; i++)
	{
		for (int j = 0; j < cols; j++)
			cout << arr[i][j] << " ";

		cout << endl;
	}

	// free memory 
	for (int i = 0; i < rows; i++) {
		delete[] arr[i];
	}
	delete[] arr;

	return 0;
}

/*
run:

0 1 2 3
1 2 3 4
2 3 4 5

*/

 





answered Apr 29, 2017 by avibootz

Related questions

1 answer 58 views
2 answers 129 views
...