/*
	Pointers to pointers.

	A dynamic two-dimensional array as a dynamic 1D array of pointers 
	in which each pointer is a dynamic 1D array. This array will be 
	accessed as any two-dimensional array, but number of elements in 
	each row may differ from one row to another.

	How to create, process, and destroy such an array.

	Dynamic two-dimensional array created in a more traditional way. 
	The number of elements in each row is the same as any other. The 
	number of columns has to be constant while the number of rows can
	be eneterd by the user. 

	How to create, process, and destroy such an array.
	
	delete is used only for dynamic variables/arrays.
	
*/

#include <iostream>
using namespace std;
int main()
{
	cout << "Enter size: ";
	int* size;
	size =  new int;
	cin >> *size;
	int ***c = new int**[*size]; // array of pointers to pointers
			// The above can be constructed as a 3D array.
	// delete c
	delete [] c;

	int **b = new int*[*size]; // array of pointers
	// Now make each pointer points to a 1D dynamic array
	for (int i = 0; i < *size; i++)
		b[i] = new int[*size];
	/* Now b becomes a two-dimensional array in which 
	the entry in row i column j is b[i][j].
	You can make the number of elements differ from 
	one b[i] to another.
	*/
	
	// Read array b:
	cout << "Enter elements: ";
	for (i = 0; i < *size; i++)
		for (int j = 0; j < *size; j++)
			cin >> b[i][j];

	// Print array b:
	for (i = 0; i < *size; i++)
	{
			for (int j = 0; j < *size; j++)
				cout << b[i][j] << '\t';
			cout << endl;
	}
	cout << endl;
	
	 // delete rows of array b
        for (i = 0; i < *size; i++)
                delete [] b[i];
        // delete array b
        delete [] b;
	
	// delete size
	delete size;
	
	int f = 5, *g = &f, **h = &g;
	// h is a pointer to a pointer
	cout << "h = " << h << "\t &g = " << &g << endl;
	cout << "**h = " << **h << endl;

	cout << g << '\t' << *h << endl;
	cout << f << '\t' << *g << '\t' << **h << endl;

	// delete g; // ERROR
	// delete h; // ERROR

	/*
		x below is a dynamic 2D in which the number of elements 
		in each row is the same in any other row.
		x has 4 rows and 2 columns
	*/
	int (*x) [2] = new int[4][2]; 
	/*
		The number of rows of x can be a variable but the 
		number of columns is constant.
`	*/

	// delete array x.
	delete [] x;
	
	return 0;
}



