How do I declare and use dynamic 2D array in C++

2 Answers

0 votes
#include <iostream>

using namespace std;

int main()
{
	const auto rows = 3;
	const auto cols = 4;

	// allocate 
	auto arr = new double[rows][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 
	delete[] arr;

	return 0;
}

/*
run:

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

*/

 



answered Apr 29, 2017 by avibootz
0 votes
#include <iostream>

using namespace std;

int main()
{
	const auto rows = 3;
	const auto cols = 4;

	// allocate 
	auto arr = new double[rows][cols]();

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

		cout << endl;
	}

	// free memory 
	delete[] arr;

	return 0;
}

/*
run:

0 0 0 0
0 0 0 0
0 0 0 0

*/

 



answered Apr 29, 2017 by avibootz

Related questions

1 answer 158 views
1 answer 137 views
1 answer 138 views
1 answer 278 views
278 views asked May 28, 2014 by Zevan
...