Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

pass a dynamic array to a function 1

Status
Not open for further replies.

stranger123

Programmer
Apr 16, 2006
76
0
0
GB
Hi,

I remember a book said we can use *& to pass an array to a function, but now I find it can be done by use * only. For example:

void main()
{
int* myArray = new int[1];
myArray[0]=1;
MyFunction(myArray);
cout<<myArray[0]<<endl;
delete[] myArray;
}
void MyFunction(int* myArray) //void MyFunction(int*& myArray)
{
myArray[0]++;
}

So, what is the difference between * and *& when pass an array to a function?

Can you help?
 
* passes a copy of a pointer.
*& passes a reference to a pointer.

Basically if MyFunction() assigned a different pointer value like this:
Code:
void MyFunction( int* myArray )
{
   delete [] myArray;
   myArray = new int[ 50 ];
}
The myArray in your main() function would still point to the same address that it did before calling MyFunction() (which is now invalid because it points to memory that was deleted).

If you changed it to *& then myArray in main() would point to the new address that was allocated by MyFunction().
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top