Pointer To Pointers

I am reading Jumping into C++ and playing around with pointers to pointers on chapter 14. I decided to make a multiplication table to play around with and learn from.

The code works but I feel I'm allocating too many pointers unnecessarily when I could just have 2 pointers branching from the original pointer-to-pointer. Could someone take a look at the (working) code and tell me how I could have it use only 2 dynamically allocated pointers instead of it making as many as the table size?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>

int main()
{
	int s;
	int **p_p_mtable;

	std::cout<<"Multiplication Table Size: ";
	std::cin>>s;
	s+=1;
	std::cout<<"\n";

	//Create dynamic pointers
	p_p_mtable = new int*[s];

	//Create arrays with dynamically allocated memory
	for (int i = 0; i < s; i++)
	{
		p_p_mtable[i] = new int[s];
	}

	//Loop through array and fill it in
	for (int i = 1; i < s; i++)
	{
		for (int j = 1; j < s; j++)
		{
			p_p_mtable[i][j] = i*j;
			std::cout<<p_p_mtable[i][j]<<"\t";
		}
		std::cout<<"\n";
	}
	std::cout<<"\n";

	//Delete arrays from heap
	for (int i = 0; i < s; i++)
	{
		delete[] p_p_mtable[i];
	}

	//Delete pointer from heap
	delete[] p_p_mtable;
	p_p_mtable = NULL;
}
You can use one int* pointer.
All you need is allocate s*s size array and access it as 2D one using integer division and modulus operators.
i.e. 2D address to 1D will be n = x*s + y and 1D to 2D: x = n / s; y = n % s;
Where x, y is indexes of virtual 2D array, n is an actual index in underlying 1D array and s is table size
Yes I'm aware I can do this much simpler or with no pointers at all but the whole point is to practice using pointers-to-pointers so I understand the syntax properly. Thanks for those handy formulas =]
Topic archived. No new replies allowed.