- #141
yungman
- 5,755
- 293
I think I got it, I need to practice more though. This is the program using pointer to pointer:
I copy the display from running the program. It ask for 5 integer, I put in 2, 3, 4, 5, 6. You can see the physical address for each element. I print out the address of Arr( same as Arr[0]), they when the function exit back to main, I printed out the content of pNumber. You can see both address match. So the pointer is PASSED back to main from the function.
Thanks
C++:
#include <iostream>
using namespace std;
void getRNum(int**, int);//return a pointer from the functionint main()
{
int size = 5;
int*pNumber = NULL;//initiate a pointer number
getRNum(&pNumber, size);//pass address of pNumber
cout << " Back to main, pNumber = " << pNumber << "\n\n";
cout << " The array pointed by pNumber = {";
for (int count = 0; count < size-1; count++)// display the numbers
cout << *(pNumber + count) << " ";
cout << *(pNumber + size-1) << "}\n\n";
delete[] pNumber;//free the memory of 5 element array number[5]
return 0;
}
void getRNum(int** pArr, int num)//receive &pNumber the addresses of pNumber.
{
int* Arr = NULL; // set pointer Arr to Null
Arr = new int[num]; //request 5 elements of int of memory from computer pointed by Arr.
*pArr = Arr;// *pArr = address of Arr[0].
for (int count = 0; count < num; count++)// input 5 integers to Arr[0..4].
{
cout << " Enter number " << count + 1 << " = ";
cin >> *(*pArr + count);//*pArr = address of Arr[0], pArr + elements = address of Arr[1...]
cout << " In memory location of Arr: " << (Arr + count) << "\n\n";
}
}
/*
Enter number 1 = 2
Enter number 1 = 2
In memory location of Arr: 012B4D50
Enter number 2 = 3
In memory location of Arr: 012B4D54
Enter number 3 = 4
In memory location of Arr: 012B4D58
Enter number 4 = 5
In memory location of Arr: 012B4D5C
Enter number 5 = 6
In memory location of Arr: 012B4D60
Back to main, pNumber = 012B4D50
The array pointed by pNumber = {2 3 4 5 6}
*/
I copy the display from running the program. It ask for 5 integer, I put in 2, 3, 4, 5, 6. You can see the physical address for each element. I print out the address of Arr( same as Arr[0]), they when the function exit back to main, I printed out the content of pNumber. You can see both address match. So the pointer is PASSED back to main from the function.
Thanks