Gunner Stone Gunner Stone - 1 year ago 82
C++ Question

How to pass Dynamic Array by reference C++

As the title suggests, I'm having trouble with Dynamic Arrays / Functions in a project of mine.

I've recreated the problem in this small code sample:

#include <iostream>

using namespace std;

void defineArray(int*);

int main()
int * myArray;

//cout<<(*(myArray)); //desired output is 0
return 0;

void defineArray(int*myArray)
int sizeOfArray;
cout<<"How big do you want your array:";

/** Dynamically allocate array with user-specified size*/
myArray=new int [sizeOfArray];

/** Define Values for our array*/
for(int i = 0; i < sizeOfArray; i++)

Any help is appreciated.

Answer Source

myArray is passed by value itself, any modification on myArray (such as myArray=new int [sizeOfArray];) has nothing to do with the original variable, myArray in main() is still dangled.

To make it passed by reference, change

void defineArray(int*myArray)


void defineArray(int*& myArray)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download