Array of Pointers to an Array

Hi,

I am teaching myself C++. I am currently writing a program to sort 10
numbers. I have the array with values working, and I can print the values
on the screen, (see output); however, when I try to print the values using
the array of pointers to the array values I get the memory addresses,
(see output). How do I fix this code so that I can dereference the pointers
and print the values. If the code is working properly both outputs should
match.


Program Output:
6 2 8 4 9
10 7 3 5 1

0x7fff3f6561e00x7fff3f6561e80x7fff3f6561f00x7fff3f6561f80x7fff3f656200
0x7fff3f6562080x7fff3f6562100x7fff3f6562180x7fff3f6562200x7fff3f656228


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
// Program that sorts numbers 1 through 10.

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
	const int size = 10;

	int numbers[size] = {6, 2, 8, 4, 9,
					10, 7, 3, 5, 1};

	int* pnumbers[size];

	for(int i = 0; i < size; i++)
		pnumbers[i] = &numbers[i];

	//output original numbers using array
	for(int i = 0; i < size; i++)
	{
		if(i % 5 == 0)	
			cout << endl;
		cout << setw(5) << numbers[i];
	}
	cout << endl;
	
	//output original numbers using pointers
	for(int i = 0; i < size; i++)
	{
		if(i % 5 == 0)	
			cout << endl;
		cout << setw(5) << (pnumbers + i);
	}
	cout << endl;

	return 0;
}
(pnumbers + i) is exactly the same &(pnumbers[i]). I think you want **(pnumbers+1), or just *(pnumbers[i]).
Cool. I really appreciate your help!

I changed line 34 to...
cout << setw(5) << **(pnumbers+i);

...and it worked perfectly.

I don't really understand why that worked.
I believe that this is pointer to pointer notation.
Am I using this notation because I am pointing to an array element?
pnumbers is an array of int*, and i is the offset you want to look at. pnumbers is the address of the first element of the array, so we start there and add i to get to the address of the element we want.

Deference that to get the i-th element. Since that is an int*, and we want the actual int, we need to dereference again.
Topic archived. No new replies allowed.