Gunner Stone Gunner Stone - 1 month ago 10
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;
defineArray(myArray);

/** CAUSES SEG FAULT*/
//cout<<(*(myArray)); //desired output is 0
return 0;
}

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

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

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


Any help is appreciated.

Answer

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)

to

void defineArray(int*& myArray)
Comments