Sunday, April 21, 2013

Programming - Passing Dynamic Memory to Functions by Reference

Needed to get the concept down for a much larger program.  Here is an example of how I used a dynamic array, (size dependent on user input... DANGER), passed it to a function, and had the function print the values back.

1:  void somefunc(int *nums, int howmuch)  
2:  {  
3:       for(int i=0;i<howmuch;i++)  
4:       {  
5:            cout << "Number 1: " << nums[i] << endl;  
6:       }  
7:  }  
8:    
9:    
10:  int main()  
11:  {  
12:       int *numbers;  
13:       int howmany;  
14:       cout << "How many: ";  
15:       cin >> howmany;  
16:       numbers = new int[howmany];  
17:       for(int i=0;i<howmany;i++)  
18:       {  
19:            cout << "Enter Number: ";  
20:            cin >> numbers[i];  
21:       }  
22:       somefunc(numbers, howmany);  
23:       Sleep(10000);  
24:  }  
25:    

The thing that caught me up was remembering not to PASS a *value, because that'd be a pointer to a pointer.  In the function declaration, you state that it's RECEIVING a pointer, so that's where you put the *.  Tricksy little functions.

No comments:

Post a Comment