2-D Array

Write your question here. See output below.
1) Why doesn't p_p_rows point to &p_rows?
2) Why are the addresses of p_p_rows[0] and p_p_rows[1] the same?

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// 2-D Multiplication Table

#include <iostream>

using namespace std;

int main()
{
	// declare and initialize variables
	int rows = 0;
	int columns = 0;
	int* p_columns;
	int* p_rows;
	int** p_p_rows;
	p_p_rows = &p_rows;

	// prompt for size of 2-D array
	cout << "Please specify how many rows: ";
	cin >> rows;

	cout << "Please specify how many columns ";
	cin >> columns;
	cout << endl;

	// array of pointers
	p_p_rows = new int*[rows];

	//  make each pointer store the address of an array of integers
	for (int i = 0; i < rows; i++)
	{
		p_p_rows[i] = new int[columns];
	}

	// initialize the elements of the 2-D array to zero
	for (int i = 0; i < rows; i++)
	{
		for (int j = 0; j < columns; j++)
		{
			p_p_rows[i][j] = 0;;
		}
	}

	// Display results
	for (int i = 0; i < rows; i++)
	{
		for (int j = 0; j < columns; j++)
		{
			cout << "row[" << i << "][" << j << "] = " << p_p_rows[i][j] << endl;
		}
	}
	cout << endl;
	// Check if working properly
	cout << "&p_p_rows = " << &p_p_rows << endl;
	cout << "p_p_rows = " << *p_p_rows << endl;
	cout << "&p_rows = " << &p_rows << endl;
//	cout << "p_row = " << p_row << endl;
	for (int i = 0; i < rows; i++)
	{
		cout << "&p_p_rows[" << i << "] = " << &p_p_rows << endl;
	}
	



}



Please specify how many rows: 2
Please specify how many columns 2

row[0][0] = 0
row[0][1] = 0
row[1][0] = 0
row[1][1] = 0

&p_p_rows = 0036FA24
p_p_rows = 007569D0
&p_rows = 0036FA30
&p_p_rows[0] = 0036FA24
&p_p_rows[1] = 0036FA24
Press any key to continue . . .
1. p_p_rows does not point to p_rows because you changed where it points to when you did this.
 
p_p_rows=new int* [rows]


2. p_p_rows[0] and p_p_rows[1], are not the same. You keep printing out the reference to the same memory address. To see the separate addresses do
 
<<&p_p_rows[i]<<endl;
Last edited on
Cody0023,

Thank you very much. In answering 1., you cleared up a misconception I had. I deleted p_p_rows = &p_rows; since it is unnecessary.

As for 2., my error was more of a brain f--t. But, thanks for catching it.

Best of all, I now know that the program works.
Topic archived. No new replies allowed.